PHP Programming/PHP Data Objects
This page or section is an undeveloped draft or outline. You can help to develop the work, or you can ask for assistance in the project room. |
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?
editThe 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
editPHP 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
External links
edit