PDO (PHP Data Object) Advantages

By August 15, 2015DATABASE, MYSQL, PHP

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:

$user = USER_NAME;
$pass = PASSWORD;
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

//Exception handling in PDO

try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
}

catch (PDOException $e) {
print "Error!: " . $e->getMessage() ."&amp;<br/>";
die();
}

 Insert query:

$sth = $dbh->prepare("INSERT INTO `table` (`id`, `title`) VALUES (:id, :title)");
$sth->execute(array(':id'    => 123,':title' => 'I am the title'));

//Select Query:

$sth = $dbh->prepare("SELECT `id`, `title` FROM `table` WHERE `id` > :country_id");
$sth->execute(array(':country_id' => 200));

$count = $sth->rowCount();
Pankaj Singh Sugara

Author Pankaj Singh Sugara

Experienced Software Engineer with a demonstrated history of working in the marketing and advertising industry. Skilled in SQL, Web Applications, PHP, WordPress, and Joomla. Strong engineering professional with a B-TECH focused in Information Technology from JCDM College of Engineering Sirsa, Haryana.

More posts by Pankaj Singh Sugara