A simple PDO example

This entry was posted by on Monday, 27 September, 2010 at


// create PDO Database connection
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
} catch(PDOException $e) {
echo $e->getMessage();
throw($e);
}
// prepare the statemant
$sql = $dbh->prepare("
SELECT
city, count(city), sum(counter) cnt
from geoip
where
country_name = :countryname
group by city;
");
// replace the bind parameters with variables
$sql->bindParam(':countryname', $countryname, PDO::PARAM_STR);
// execute the statemant
$sql->execute();
// check for errors - PDO catches them silently
if ($sql->errorCode() != '0000' ) {
$msg = $sql->errorInfo();
throw new Exception($msg[2]);
}
// iterate over the results
foreach ($sql as $row) {
echo "access via index: " . $row[0] . "\n";
echo "access via associative array: " . $row["cnt"] . "\n";
}


Leave a Reply