PHP PDO

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for PHP to access databases.

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

PDO was released with PHP 5.1 and is also available in the PECL extension for PHP 5.0; it cannot run on earlier PHP versions.


PDO Installation

You can use PHP's phpinfo() function to check whether the PDO extension is installed.

Installing PDO on Unix Systems

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

extension=pdo.so

Windows Users

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

extension=php_pdo.dll
In addition, there are the following corresponding 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 these configurations, we need to restart PHP or the web server.

Next, let's look at a specific example. The following is an example of using PDO to connect to a MySQL database:

Example

<?php
$dbms='mysql';     //database type
$host='localhost'; //database host name
$dbName='test';    //database used
$user='root';      //database connection username
$pass='';          //corresponding password
$dsn="$dbms:host=$host;dbname=$dbName";


try {
    $dbh = new PDO($dsn, $user, $pass); //initialize a PDO object
    echo "Connection successful<br/>";
    /*You can also perform a search operation
    foreach ($dbh->query('SELECT * from FOO') as $row) {
print_r($row); //you can use echo($GLOBAL); to see these values
    }
    */

    $dbh = null;
} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}
//By default, this is not a persistent connection. If you need a persistent database connection, you need to add a parameter at the end: array(PDO::ATTR_PERSISTENT => true) like this:
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));

?>

Very simple. Next, let's take a closer look at the specific documentation for PHP PDO:

Other Extensions