William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP PDO

PDO is PHP Data Objects. It is an option for database access, besides MySQLi, mdb2.

1. How to activate PDO

PDO is installed with PHP by default; by edit PHP config file to activate it.
In my CentOS server env, the config file is at /etc/php.d/pdo.ini.

// in /etc/php.d/pdo.ini:
// Enable pdo extension module
extension=pdo.so
...
// restart web server, and PDO can be found by:
$ php -r 'phpinfo();' |grep -i pdo
//enabled: mysql,odbc,pgsql,sqlite

2. injection security

A benefit to use PDO is anti-injection. It has prepared statements and placeholder to escape the input strings, like this:


$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
//using bindParam()
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
$stmt->execute();
//or:
$stmt->execute(array($name, $value));

This is very cool, useful for registry, login checking, etc in which security is more important.

3. Singleton

DB access needs Singleton feature. A singleton PDO wrapper example:


class DB {    
 private static $instance=null; 
 private function __construct() {}
 public static function getInstance() { 
  if(!self::$instance){ 
  	// use constant variables.
	self::$instance = new PDO(DB_DSN, DB_USER, DB_PASS); 
	self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
  } 
  return self::$instance; 
 } 

 /* Passes on any static calls to this class onto the singleton PDO instance */ 
 final public static function __callStatic($method,$args) 
 { 		
  $instance = self::getInstance(); 

  return call_user_func_array(array($instance, $method), $args); 	
 }   
}

// Use it:
$stmt = DB :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute( ) ;
var_dump ( $stmt->fetchAll ( ) ) ;
$stmt -> closeCursor( ) ;

4. PDO vs.MySQLi

The following is a comparation between PDO and MySQLi:

PDO MySQLi
Database support 12 different drivers MySQL only
API OOP OOP + procedural
Connection Easy Easy
Named parameters Yes No
Object mapping Yes Yes
Prepared statements
(client side)
Yes No
Performance Fast Fast
Stored procedures Yes Yes
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: