• My PHP Pages

    This is a complete and free PHP programming course for beginners. Everything you need to get started is set out in section one below.

Jul 5, 2013

Posted by Unknown
4 comments | 7:37 AM

Most of the PHP developers using Mysql or Mysqli php functions when they work with databases. but PHP has introduced new extension call PDO in PHP 5.1. this methord is way better and very productive. PDO is stands for PHP Data Objects. 

Note : Mysql functions is removed from PHP 5.5. so its better to use PDO or Mysqi. I strongly recommend to use PDO.



PDO Supported Databases Drivers List


You can use bellow code to find which driver is installed on your system.
 print_r(PDO::getAvailableDrivers()); 
  1. PDO_DBLIB ( FreeTDS / Microsoft SQL Server / Sybase )
  2. PDO_FIREBIRD ( Firebird/Interbase 6 )
  3. PDO_IBM ( IBM DB2 )
  4. PDO_INFORMIX ( IBM Informix Dynamic Server )
  5. PDO_MYSQL ( MySQL 3.x/4.x/5.x )
  6. PDO_OCI ( Oracle Call Interface )
  7. PDO_ODBC ( ODBC v3 (IBM DB2, unixODBC and win32 ODBC) )
  8. PDO_PGSQL ( PostgreSQL )
  9. PDO_SQLITE ( SQLite 3 and SQLite 2 )
  10. PDO_4D ( 4D )



Lets Connect to the database using PDO


Note :  Different database drivers may have different connection methods. i am not going to all of them i will just explain how to connect with most common databases.








Connect Mysql using PDO_Mysql

$user = "root";
$pass="";
$host="localhost";
$dbname="my_db";
try
{
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOexception $e)
{
echo $e->getMassage();
}



Connect Ms Sql Server Using PDO

$user = "root";
$pass="";
$host="localhost";
$dbname="my_db";
try
{
$DBH = new PDO("mssql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOexception $e)
{
echo $e->getMassage();
}

Connect Sybase using PDO

$user = "root";
$pass="";
$host="localhost";
$dbname="my_db";
try
{
$DBH = new PDO("mybase:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOexception $e)
{
echo $e->getMassage();
}

Connect SQLite using PDO

try
{
$DBH = new PDO("sqlite:my/database/path/database.db");  
}
catch(PDOexception $e)
{
echo $e->getMassage();
}

Close PDO Connection

$DBH = null;


Every time you use PDO, use it inside try catch statement. cheers...




4 comments :