Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP PDO


May 11, 2021 PHP


Table of contents


PHP PDO

The PHP Data Object (PDO) extension defines a lightweight, consistent interface for PHP access to the database.

PDO provides a layer of data access abstraction, which means that the same functions (methods) can be used to query and obtain data, regardless of the database used.

The PDO is released with PHP 5.1 and can also be used in the PECL extension of PHP 5.0 and cannot run on previous PHP versions.


PDO installation

You can see if the PDO extension is installed through PHP's phpinfo() function.

Install the PDO on the Unix system

On Unix or Linux you need to add the following extensions:

extension=pdo.so

Windows users

PDO and all major drivers are published with PHP as shared extensions, and to activate them simply edit the php .ini file and add the following extensions:

extension=php_pdo.dll

In addition to the following corresponding various database extensions:

;extension=php_pdo_firebird.dll
;extension=php_pdo_informix.dll
;extension=php_pdo_mssql.dll
;extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_oci8.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll

After setting up these configurations, we need to restart PHP or web servers.

Let's look at the specific examples, the following is an example of connecting to the MySql database using PDO:

<?php 
$dbms='mysql';     //数据库类型 
$host='localhost'; //数据库主机名 
$port='3306';      //数据库端口
$dbName='test';    //使用的数据库 
$user='root';      //数据库连接用户名 
$pass='';          //对应的密码 
$dsn="$dbms:host=$host;port=$port;dbname=$dbName";   
try {     
$dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象     
echo "连接成功<br/>";
    /*你还可以进行一次搜索操作
    foreach ($dbh->query('SELECT * from FOO') as $row) {
        print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
    }
    */
    $dbh = null;
} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}
//默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样:
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));

?>

Quite simply, let's take a look at the PHP PDO description: