PDO (PHP Data Object)

PDO(PHP Data Object)  : PDO is a PHP extension for accessing databases in PHP.

Advantages:

1) Security : In MYSQL connection we manually sanitise using mysql_real_escape_string() functions in order to avoid SQL injections. But with PDO this is all taken care for us and means we no longer have to worry about SQL injection.

2) Performance : PDO uses PHP 5′s OOP characteristics (Object Oriented Programming) so it is working with classes and objects. PDO is written in C and compiled into PHP providing a performance increase over solutions written in PHP.

3) PDO provides single interface across multiple databases. That means to easily migrate to a different database engine (SQLite, Oracle, MSSQL, ODBC, etc.)

4) We can use error handling in PDO by using try, catch and throw.

Connection Syntex:
[php]
$user = USER_NAME;

$pass = PASSWORD;

$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);

<b>Exception handling in PDO:</b>

try {

$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);

}

catch (PDOException $e) {

print "Error!: " . $e-&gt;getMessage() . "&lt;br/&gt;";

die();

}
[/php]

 Insert query:
[php]
$sth = $dbh-&gt;prepare("INSERT INTO `table` (`id`, `title`) VALUES (:id, :title)");

$sth-&gt;execute(array(‘:id’    =&gt; 123,’:title’ =&gt; ‘I am the title’));

<b>Select Query:</b>

$sth = $dbh-&gt;prepare("SELECT `id`, `title` FROM `table` WHERE `id` &gt; :country_id");

$sth-&gt;execute(array(

‘:country_id’ =&gt; 200

));

$count = $sth-&gt;rowCount();
[/php]

Leave a Reply