PHP PDO
HP Data object is a database connection abstraction library for PHP 5.
What is PDO ?
- Its written in complied language(c/c++) , other php libraries are written in Interpreted language (AdoDB , PEAR DB)
- its lightweight database connection abstraction library
WHY PDO ?
- It support many databases , so you don’t need to write lines of code of each database , just write one code and run on any database
- Speed . PDO is written in complied language but others php libraries like PEAR DB ,Adodb are written in interpreted language.
PHP supports many databases like mysql , sqllite , postgre sql etc.
mysql_connect($host,$user,$password)
sqllite_open($host,$user,$password)
pg_connect($host,$user,$password)
so if you have to change your database from say mysql to postgre or viceversa , then you have to change your code , so you have to do rework on that.
thats way PDO cam ein picture , so that you have to write just one code and it will be work on any database platform without changing codes again and again.
PDO: Activation PHP Data Objects Extension
Goto PHP/ext folder and check whether pdo extension exists or not.
php_pdo.dll , php_pdo_mysql.dll etc.
To enable PDO , go to PHP.INI file and uncommnet the code
;extension=php_pdo.dll -> extension=php_pdo.dll
;extension=php_mysql_pdo.dll -> extension=php_mysql_pdo.dll
Restart your apache server.
PDO: connection to databases
//mysql connection
$con = new PDO(‘mysql:host=$host,dbname=$DB’,$user,$pwd);
//sqllite connection
$con = new PDO(‘sqllite:$DB’);
//postgre connection
$con = new PDO(‘pqsql:host=$host,dbname=$DB’,$user,$pwd);
or we can write like this also
<?php
// configuration
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
$dbpath = "c:/test.db";
// switching
switch($dbtype){
case "mysql":
$dbconn = "mysql:host=$dbhost;dbname=$dbname";
break;
case "sqlite":
$dbconn = "sqlite:$dbpath";
break;
case "postgresql":
$dbconn = "pgsql:host=$host dbname=$db";
break;
}
// database connection
$conn = new PDO($dbconn,$user,$pass);
?>
PDO: Fetch Mode
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT title FROM books ORDER BY title";
$q = $conn->query($sql);
// fetch
while($r = $q->fetch()){
print_r($r);
}
// result //Array ( [title] => PHP AJAX [0] => PHP AJAX )
// query
$sql = "SELECT title FROM books ORDER BY title";
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC); //fetch association
// fetch
while($r = $q->fetch()){
print_r($r);
}
// result //Array ( [title] => PHP AJAX)
$q->setFetchMode(PDO::FETCH_NUM);
// fetch
while($r = $q->fetch()){
print_r($r);
}
// result //Array ( [0] => PHP AJAX )
$q->setFetchMode(PDO::FETCH_BOTH);
$q = $conn->query($sql);
// fetch
while($r = $q->fetch()){
print_r($r);
}
// result //Array ( [title] => PHP AJAX [0] => PHP AJAX )