PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data.
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}
// Persistent Connections
true
));
?>
Prepared Statements :
They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
a) The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters.
b) The parameters to prepared statements don’t need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// repeated inserts
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// fetching data
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
PDO vs mysqli :
While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements.
PDO works with several databases whereas MySQLi works with MySQL only.
PDO has named parameters whereas MySQLi does not.
$pdo->prepare(‘SELECT * FROM users WHERE username = :username AND email = :email’);
$params = array(‘:username’ => ‘test’, ‘:email’ => $mail);
$mysqli->prepare(‘SELECT * FROM users WHERE username = ? AND email = ?’);
$query->bind_param(‘test’, $mail);
http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use–net-24059