Here are some of the basic syntax for using PDO Objects.
The advantage of PDO objects is that you pass your variables into the SQL function using prepared statements.
Prepared statements are what are termed paramatised queries when working with program languages like Microsoft dot.net and
provide a way to prevents sql injection into databases.
SQL FETCH
<?php
$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);
$stmt = $dbh->prepare(“SELECT * FROM REGISTRY where name = ?”);
if ($stmt->execute(array($_GET[‘name’]))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
SQL MODIFY
<?php
$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);
$stmt = $dbh->prepare(“INSERT INTO REGISTRY (name, value) VALUES (?, ?)”);
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);// insert one row
$name = ‘one’;
$value = 1;
$stmt->execute();// insert another row with different values
$name = ‘two’;
$value = 2;
$stmt->execute();
?>
It is advisable to use try / catch statements around PDO or and print out friendly error messages or otherwise it is
possible that an error will display internal details that you don’t want users to see.
<?php
try {
$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);
foreach($dbh->query(‘SELECT * from table’) as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}
?>