9.6.1 Quick PEAR::DB callsThis is NOT the latest copy of this book; click here for the latest version.
PEAR::DB has three special functions that are designed to make very simple SQL queries easy to use from within PHP. These functions are getOne(), getRow(), and getCol(), and each take an SQL query to execute as their parameter. GetOne() executes the query, then returns the first row of the first column of that query, getRow() returns all columns of the first row in the query, and getCol() returns the first column of all rows in the query. GetOne() returns just one value, whereas getRow() and getCol() both return arrays of values.
Here is an example demonstrating each of these functions in action, using the people table created earlier:
<?php
include_once('DB.php');
$db = DB::connect("mysql://root:alm65z@localhost/phpdb");
if (DB::isError($db)) {
print $db->getMessage();
exit;
} else {
$maxvisits = $db->getOne("SELECT MAX(NumVisits) FROM people;");
print "The highest visit count is $maxvisits<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(); ?>
As you can see, using these three "quick access" functions mean you do not need to bother with anything more than just one simple function call.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|