Using PDO (Php Data Objects)


A php programmer typically starts coding by learning how to use mysql_* or mysqli_* functions for database access. With Php 5.1, there is a better way of doing db calls using PDO or PHP Data Objects.  Lets analyse why:

  • Better portability – You can use it over many db layers like MSSql, Mysql etc. You need not change the code each time.
  • Prevents SQL Injections – With PDO you can uses binded params and that will prevent most sql injection attacks.
  • Object Oriented Interface

It is fairly simple to start using PDO

  • Making connection 
    $dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE, DB_USER,DB_PASSWORD,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false,PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'));
    }catch(PDOException $ex){
    file_put_contents('/tmp/PDOErrors.txt', $e->getMessage(), FILE_APPEND);
  • Preparing Query    
     $sth = $dbh->prepare("select from employees where name=:name"); 
    Here :name is a parameter that you need to bind with the value.
  • Bind param to value  
  • Set…

View original post 27 more words


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s