Examples of using PDO objects in PHP

<?php

//Example of fetching data from a database using PDO objects

# using the shortcut ->query() method here since there are no variable
# values in the select statement.

try {

$dbhost = “localhost”;
$dbname    = “users”;
$dbusername = “root”;
$dbpass = “”;

//Connect to the database
$dbh = new PDO(“mysql:host=” . $dbhost . “;dbname=” . $dbname, $dbusername, $dbpass);

//the sql query
$sql = “SELECT * FROM users”;

//statment handle
$sth = $dbh->query($sql);

# setting the fetch mode
$sth->setFetchMode(PDO::FETCH_ASSOC);

echo(“——————————————–<br/>”);
echo(“An example of a while loop<br/>”);
while($row = $sth->fetch()) {
echo( $row[“first_name”] . “<br/>” );
$table[] = $row;
}

$dbh = null;

}  catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}

echo(“<br/><br/>”);

echo(“——————————————–<br/>”);
echo(“An example of looping around an array<br/>”);

if ($table) {    //Check if there are any rows to be displayed
//Retrieve each element of the array
foreach($table as $d_row) {
echo( $d_row[“first_name”] . ” ” . $d_row[“last_name”] . “<br/>” );
}
}

echo(“——————————————–<br/>”);
echo(“An example of printing one element from the array<br/>”);
echo($table[0][“first_name”]);

?>

<?php

//Example of fetching data from a database using PDO objects

//This uses a prepared statement using named values

try {

$dbhost = “localhost”;
$dbname    = “users”;
$dbusername = “root”;
$dbpass = “”;

$first_name = “%paul%”;

//Connect to the database
$dbh = new PDO(“mysql:host=” . $dbhost . “;dbname=” . $dbname, $dbusername, $dbpass);

//the sql query using a named placeholder
$sql = “SELECT * FROM users WHERE first_name LIKE :first_name “;

//statment handle
$sth = $dbh->prepare($sql);

$sth->execute(array(“:first_name” => $first_name));

$sth->setFetchMode(PDO::FETCH_ASSOC);

echo(“<br/><br/>”);
echo(“——————————————–<br/>”);
echo(“An example of printing values from a select statement with parameters<br/>”);

while($row = $sth->fetch()) {
echo( $row[“first_name”] . “<br/>” );
$table[] = $row;
}

$dbh = null;

}  catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}

?>

Leave a Reply