PDO basic MySQL tutorial, pdomysql basic tutorial

Source: Internet
Author: User

PDO basic MySQL tutorial, pdomysql basic tutorial

The PDO extension in PHP defines a lightweight and consistent interface for PHP to access the database. It provides a data access abstraction layer so that no matter what database is used, you can use consistent functions to query and obtain data.

The PHP version supported by PDO is PHP5.1 and later. In PHP5.2, PDO is enabled by default,

The following is the PDO configuration in php. ini:

Extension = php_pdo.dll


To enable support for a database, you need to open the corresponding extension in the php configuration file. For example, to support MySQL, You need to enable the following extension.

Extension = php_pdo_mysql.dll


The following describes how to use PDO to add, delete, modify, and query mysql.
Create the test database and run the following SQL statement:

Drop table if exists 'test ';
Create table 'test '(
'Id' int (10) not null default '0 ',
'User' char (20) default null,
Primary key ('id '),
KEY 'idx _ age' ('id ')
) ENGINE = InnoDB default charset = utf8;


Program code:

<? Php
Header ("content-type: text/html; charset = UTF-8 ");
$ Dsn = "mysql: dbname = test; host = localhost ";
$ Db_user = 'root ';
$ Db_pass = 'admin123 ';
Try {
$ Pdo = new PDO ($ dsn, $ db_user, $ db_pass );
} Catch (PDOException $ e ){
Echo 'database connection failed'. $ e-> getMessage ();
}
// Add
$ SQL = "insert into test (id, user) values (1, 'phpthinking ')";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;
// Modify
$ SQL = "update test set user = 'phpthinking' where id = 1 ";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;
// Query
$ SQL = "select * from test ";
$ Res = $ pdo-> query ($ SQL );
Foreach ($ res as $ row ){
Echo $ row ['user']. '<br/> ';
}
// Delete
$ SQL = "delete from test where id = 1 ";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.