PHP Data Object - PDO

by saravana 2013-07-23 15:18:30


PHP Data Object/PDO TOC Step By Step Tutorial PHP Data Object is a Database Connection Abstraction Library for PHP 5.

What is PDO?

->a PHP5 extension written in a compiled language (C/C++)
->a Lightweight DBMS connection abstract library (data access abstraction library)

Why PDO?

->Support great number of database systems supported by PHP
->You don't need rewriting of many line code for each database. Just write one and run anywhere
->Speed. PDO written in compiled language, PHP libraries (ADOdb, PEAR DB) written in an interpreted language
->Your software more easy to install. Do not need third party software

Whenever you need PDO?

->You need portable application that support many database system
->You need speed

Syntax with Error handling:

try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}


Prepared Statement with Example:

$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));

while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}


Thoughts:

If you are still using that old mysql API for connecting to your databases, stop. Your code will be significantly more secure and streamlined if you adopt the PDO extension.
598
like
0
dislike
0
mail
flag

You must LOGIN to add comments