PDO (PHP Data Objects)

What is PDO? 

PDO, the PHP Data Objects extension, is a data-access abstraction layer. But what the heck is that? Basically, it’s a consistent interface for multiple databases. No longer will you have to use the mysql_* functions, the sqlite_* functions, or the pg_* functions, or write wrappers for them to work with your database. 

Instead, you can simply use the PDO interface to work with all three functions using the same methods. And, if you change databases, you’ll only have to change the DSN (or Data Source Name) of the PDO to make your code work. 

PDO uses specific database drivers to interact with various databases, so you can’t use PDO by itself. You’ll need to enable the drivers you’ll use with PDO, so be sure to research how to do it for your specific host operating system on the PDO manual page.

PDO is shipped with PHP 5.1 and is available from PECL for PHP 5.0. Unfortunately, as PDO equires the new PHP 5 object oriented features, it’s not available for PHP. Here all of our interactions with the database will use PDO to interact with the MySQL back end.


How do I access a database? 

Before we can do anything with a database, we need to talk to it. And to talk to it, we must make a database connection. Logical, isn’t it?

Solution 
Here’s how we connect to a MySQL database on the localhost:

<?php
$dsn = 'mysql:host=localhost;dbname=world;';
$user = 'user';
$password = 'secret';
try
{
$dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>

We’d use this code to connect to a SQLite database on the localhost:

<?php
$dsn = 'sqlite2:"C:\sqlite\world.db"';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>


And this code will let us connect to a PostgreSQL database on the localhost:

<?php
$dsn = 'pgsql:host=localhost port=5432 dbname=world user=user ';
$dsn .= 'password=secret';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>


Notice that in all three examples above, we simply create a new PDO object. Only the connection data for the PDO constructor differs in each case: for the SQLite and PostgreSQL connections, we need just the DSN; the MySQL connection also requires username and password arguments in order to connect to the database.

Comments

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb

Add and delete columns dynamically in an HTML table