PHP/Utility Function/PEAR
Advanced PEAR::DB: Prepared Statements
include_once("DB.php");
$db = DB::connect("mysql://user:password@localhost/phpdb");
if (DB::isError($db)) {
print $db->getMessage( );
exit;
} else {
$data = array(
array("Gabor", 25),
array("Elisabeth", 39),
array("Vicky", 19)
);
$prep = $db->prepare("INSERT INTO people VALUES (?, ?);");
while(list($var, $val) = each($data)) {
print "Adding element $var\n";
$db->execute($prep, $val);
}
}
$db->disconnect( );
PEAR::DB
include_once("DB.php");
$conninfo = "mysql://username:password@localhost/phpdb";
$db = DB::connect($conninfo);
if (DB::isError($db)) {
print $db->getMessage( );
exit;
}
$result = $db->query("SELECT * FROM people;");
while ($result->fetchInto($row, DB_FETCHMODE_ASSOC)) {
extract($row);
print "$Name: $NumVisits\n";
}
$result->free( );
$db->disconnect( );
Quick PEAR::DB Calls
include_once("DB.php");
$db = DB::connect("mysql://user:password@localhost/phpdb");
if (DB::isError($db)) {
print $db->getMessage( );
exit;
} else {
$maxage = $db->getOne("SELECT MAX(Age) FROM people;");
print "The highest age is $maxage<br />";
$allnames = $db->getCol("SELECT Name FROM people;");
print implode(", ", $allnames) . "<br />";
$onecol = $db->getRow("SELECT * FROM people WHERE Name = "Ildiko";");
var_dump($onecol);
}
$db->disconnect( );