SoFunction
Updated on 2025-03-09

php uses PDO to operate MySQL database instance

This article describes the method of using PDO to operate MySQL database. Share it for your reference. The specific analysis is as follows:

PDO is a common class for mysql database operations. We do not need to customize the class to directly use pdo to operate the database. However, in the default configuration of PDO, we must enable it in the first place before we can use it. Here is a detailed introduction.

The PDO extension defines a lightweight, consistent interface for PHP access databases. It provides a data access abstraction layer, so that no matter what database is used, queries and data can be executed through consistent functions.

The PHP version supported by PDO is PHP5.1 and higher, and PDO is enabled by default under PHP5.2.

Here is the configuration of PDO in the following:

Copy the codeThe code is as follows:
extension=php_pdo.dll

In order to enable support for a certain database, the corresponding extension needs to be opened in the php configuration file. For example, to support MySQL, the following extensions need to be enabled:

Copy the codeThe code is as follows:
extension=php_pdo_mysql.dll

Here is a basic addition, deletion, modification and search operation for mysql using PDO. The PHP program code is as follows:

Copy the codeThe 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 new
$sql="insert into buyer (username,password,email) values ('ff','123456','admin@')";
$res=$pdo->exec($sql);
echo 'affect number of rows:'.$res;
 
//Revise
$sql="update buyer set username='ff123' where id>3";
$res=$pdo->exec($sql);
echo 'affect number of rows:'.$res;
//Inquiry
$sql="select * from buyer";
$res=$pdo->query($sql);
foreach($res as $row){
 echo $row['username'].'<br/>';
}
//delete
$sql="delete from buyer where id>5";
$res=$pdo->exec($sql);
echo 'affect number of rows:'.$res;

I hope this article will be helpful to everyone's PHP programming.