Introduction to PHP PDO (PHP Data Objects)

Article By priyanka01


What is PDO (PHP Data Objects).

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO PHP Data Objects interface can expose database-specific features as regular extension functions.

Note that you cannot perform any database functions using the PDO PHP Data Objects extension by itself; you must use a database-specific PDO driver to access a database server.

PDO PHP Data Objects provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.

What databases does PDO support?

PDO PHP Data Objects supports many of the popular databases as seen on the list below.

  • DBLIB: FreeTDS / Microsoft SQL Server / Sybase
  • Firebird ( Firebird/Interbase 6
  • IBM (IBM DB2)
  • INFORMIX - IBM Informix Dynamic Server
  • MYSQL ( MySQL 3.x/4.0
  • OCI ( Oracle Call Interface
  • ODBC: ODBC v3 (IBM DB2 and unixODBC)
  • PGSQL ( PostgreSQL
  • SQLITE ( SQLite 3.x

To see if the PDO driver is available for your database, check phpinfo() and you should have a section named PDO and another pdo_mysql or pdo_sqlite depending on your choice of database. You may also check the available drivers with the static method PDO::getAvailableDrivers().


Connect to database.

Here we connect to a MySQL database with PDO


Close a Database Connection

Up to this point we have seen how to connect to a database using PDO. But of course, we also need to disconnect when we have finished. To close the connection the object needs to be destroyed so that no reference to it remains. This is normally done at the end of a script where PHP will automatically close the connection. However, the connection may be close implicitly by assigning the value of null to the object as seen below.

/*** close the database connection ***/
 $db = null;
 catch(PDOException $e)
 echo $e->getMessage();

If the database connection fails, the code to assign a null value is never called as the exception throws control to the catch block.

Tags: ,

Spin Up A VPS Server In No Time Flat

Simple Setup

Full Root Access

Straightforward Pricing


Leave a Reply