PHP Programming/PHP Data Objects

The information given here is not applicable to all versions of PHP
Versions applicable: PHP 5.0 and above
The PHP Data Objects extension requires features that were introduced in PHP 5.0, and will not be available to users of PHP 4.x and below.

PHP Data Objects, also known as PDO, is an interface for accessing databases in PHP without tying code to a specific database. Rather than directly calling mysql_, mysqli_, and pg_ functions, developers can use the PDO interface, simplifying the porting of applications to other databases.

How do I get it?

edit

The PHP Data Objects extension is currently included by default with installations of PHP 5.1. It is available for users of PHP 5.0 through PECL, but does not ship with the base package.

PDO uses features of PHP that were originally introduced in PHP 5.0. It is therefore not available for users of PHP 4.x and below.

Differences between PDO and the MySQL extension

edit

PHP Data Objects has a number of significant differences to the MySQL interface used by most PHP applications on PHP 4.x and below:

  • Object-orientation. While the mysql extension used a number of function calls that operated on a connection handle and result handles, the PDO extension has an object-oriented interface.
  • Database independence. The PDO extension, unlike the mysql extension, is designed to be compatible with multiple databases with little effort on the part of the user, provided standard SQL is used in all queries.
  • Connections to the database are made with a Data Source Name, or DSN. A DSN is a string that contains all of the information necessary to connect to a database, such as 'mysql:dbname=test_db'.

PHP Data Objects usage example

edit
$dsn = 'mysql:dbname=database_name;host=localhost';
$dbuser = 'database_user';
$dbuserpw = 'database_user_password';

try
{
    $connection = new PDO($dsn, $dbuser, $dbuserpw);
}
catch (PDOException $e)
{
    echo 'There was a problem connecting to the database: ' . $e->getMessage();
}

$query = $connection->query("SELECT * FROM table"); // querying the database

For more information on data source names and the elements in a DSN string for a specific PDO driver (such as MySQL and PostgreSQL), see PHP: PDO Drivers - Manual

edit