Latest web development tutorials


PHP Data Objects (PDO) extension defines a lightweight, consistent interface PHP database access.

PDO provides a data access abstraction layer, which means that, no matter what kind of database, you can query and retrieve data using the same functions (methods).

PDO with PHP5.1 issued in PHP5.0 the PECL extension may also be used, you can not run on earlier versions of PHP.

PDO installation

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

Installation on Unix systems PDO

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

Windows users

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

In addition there are the following extensions corresponding to various databases:


After set up these configurations, we need to restart PHP or Web server.

Next we look at their specific examples, the following examples use PDO to connect MySql database:

$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='test';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='';          //对应的密码

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));


Very simple, then let us look at the specific PHP PDO specify: