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;