This article mainly introduces the use of PDO in php to operate MySQL databases. the instance analyzes the basic operation methods such as enabling PDO and adding, deleting, modifying, and querying MySQL databases, which has some reference value, for more information about how to use PDO to operate MySQL databases in php, see the following example. Share it with you for your reference. The specific analysis is as follows:
PDO is a public class for mysql database operations. we can directly use pdo to operate databases without having to customize classes, but in the default php configuration, pdo is not enabled, so we must first in php. enable it in ini. here we will introduce it in detail.
The PDO extension 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:
The code is as follows:
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:
The code is as follows:
Extension = php_pdo_mysql.dll
Here we use PDO to add, delete, modify, and query mysql. The PHP program code is as follows:
The code is as follows:
Header ("content-type: text/html; charset = utf-8 ");
$ Dsn = "mysql: dbname = test; host = localhost ";
$ Db_user = 'root ';
$ Db_pass = 'admin ';
Try {
$ Pdo = new PDO ($ dsn, $ db_user, $ db_pass );
} Catch (PDOException $ e ){
Echo 'database connection failed'. $ e-> getMessage ();
}
// Add
$ SQL = "insert into buyer (username, password, email) values ('FF ', '000000', 'admin @ admin.com ')";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;
// Modify
$ SQL = "update buyer set username = 'ff123' where id> 3 ";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;
// Query
$ SQL = "select * from buyer ";
$ Res = $ pdo-> query ($ SQL );
Foreach ($ res as $ row ){
Echo $ row ['username'].'
';
}
// Delete
$ SQL = "delete from buyer where id> 5 ";
$ Res = $ pdo-> exec ($ SQL );
Echo 'number of affected rows: '. $ res;
I hope this article will help you with php programming.