Wednesday, 3 December 2014

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:
$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() . "<br/>";
    die();
 }

 Prepare query:

 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();

No comments: