PDO : PHP Data Object

PDO : PHP Data Object

PDO is an acronym for PHP Data Objects.
It is a database access layer providing a uniform method of access to multiple databases.

Use of PDO :
Let a suppose you need to connect your database to Oracle or IBM DB2 in your existing code(written in MySQL/PHP) or if you want to use/connect 2 types of database on different platforms in your project,then in that case you have to use so many APIs and it will very annoying, second option is simply use PDO extension/library for all the database related stuff.It will very easy to use and work fast rather then the traditional code.

PDO is available in PHP5.1 or more,It’s written in C,so you know it’s fast.
PDO is simply PHP extension to formalize PHP’s database connections by creating a uniform interface.This allows developers to create code which is portable across many databases and platforms.

The extension can support any database that a PDO driver has been written for.You can get available drivers by the code.
<?php
foreach(PDO::getAvailableDrivers() as $driver)
{
echo $driver.'<br/>’;
}
?>

There are so many Predefined Constants available in PDO.Below is the list of some(MYSQL) of those.These are very useful during the coding and database program.

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY
PDO::MYSQL_ATTR_LOCAL_INFILE
PDO::MYSQL_ATTR_INIT_COMMAND
PDO::MYSQL_ATTR_READ_DEFAULT_FILE
PDO::MYSQL_ATTR_READ_DEFAULT_GROUP
PDO::MYSQL_ATTR_MAX_BUFFER_SIZE
PDO::MYSQL_ATTR_DIRECT_QUERY
PDO::MYSQL_ATTR_FOUND_ROWS
PDO::MYSQL_ATTR_IGNORE_SPACE
PDO::MYSQL_ATTR_COMPRESS

We can connect any of the database using PDO, here is the example of MySQL and Oracle.
Connect to MySQL

<?php
$hostname = ‘localhost’;
$username = ‘username’;
$password = ‘password’;

try {
$dbh = new PDO(“mysql:host=$hostname;dbname=mysql”, $username, $password);
echo ‘Connected to database’;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

Connect to Oracle
<?php
try {
$dbh = new PDO(“OCI:”, “username”, “password”)
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>

All the database related commands create/update/insert/delete/alter/rename/drop are available in PDO.
The new PHP Frameworks and the PHP Open-source new versions uses PDO.

For more information and complete guide of PDO, you can go to the below links.
http://www.php.net/manual/en/book.pdo.php

http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html

Leave a Reply

Your email address will not be published. Required fields are marked *