Tuesday, December 23, 2014

PDO in PHP

PHP Data Object is what PDO stands for, PDO defines a lightweight, consistent interface that is used for accessing database in PHP. No data functions can be performed or brought in use only using PDO but a database specific PDO driver should be used instead to access a database server. PDO is latest and it is only available  after PHP 5.1 version. PDO makes it easier and convenient and provides a data-access abstraction layer this helps using multiple database  with same function query to fetch the data.

Databases supported by PDO :

Driver name
Supported databases
PDO_CUBRID
Cubrid
PDO_DBLIB
FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD
Firebird
PDO_IBM
IBM DB2
PDO_INFORMIX
IBM Informix Dynamic Server
PDO_MYSQL
MySQL 3.x/4.x/5.x
PDO_OCI
Oracle Call Interface
PDO_ODBC
ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL
PostgreSQL
PDO_SQLITE
SQLite 3 and SQLite 2
PDO_SQLSRV
Microsoft SQL Server / SQL Azure
PDO_4D
4D


Below here is a simple example of PDO :

Example:

PHP Code(connection.php)

 <?php  
 $dsn = 'mysql:dbname=ft;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
   if ($db) {  
     echo "Successfully connected to database.";  
   }  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 ?>  
 PHP PDO Insert:  
 PHP Script (insert.php):  
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->prepare("INSERT INTO test(id, message) VALUES (:id, :mgs)");  
 $data = array(  
   ':id' => 'first',  
   ':msg' => 'this is first message'  
 );  
 echo $sth->execute($data);  
 ?> 
File to get or fetch records ( PHP PDO getting record):

PHP Script (records.php)
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->query("SELECT * FROM test");  
 print_r($sth->fetch());  
 ?> 

No comments:

Post a Comment