Database Details and PHP
(Page 1 of 4 )
Picking up from where we left off last week, we'll be discussing shortcuts, query responses, metadata, and more. This article is excerpted from chapter eight of the book
Programming PHP, Second Edition, written by Kevin Tatroe, Rasmus Lerdorf, and Peter MacIntyre (O'Reilly, 2006; ISBN: 0596006810). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Shortcuts
PEAR DB provides a number of methods that perform a query and fetch the results in one step: getOne(), getRow(), getCol(),getAssoc(), andgetAll(). All of these methods permit placeholders.
ThegetOne()method fetches the first column of the first row of data returned by an SQL query:
$value = $db->getOne(SQL [, values ]);
For example:
$when = $db->getOne("SELECT avg(pub_year) FROM books");
if (DB::isError($when)) {
die($when->getMessage());
}
echo "The average book in the library was published in $when";
The average book in the library was published in 1974
ThegetRow()method returns the first row of data returned by an SQL query:
$row = $db->getRow(SQL [, values ]]);
This is useful if you know only one row will be returned. For example:
list($title, $author) = $db->getRow(
"SELECT books.title,authors.name FROM books, authors
WHERE books.pub_year=1950 AND books.authorid=authors.authorid");
echo "($title, written by $author)";
(I, Robot, written by Isaac Asimov)
The getCol() method returns a single column from the data returned by an SQL query:
$col = $db->getCol(SQL [, column [, values ]]);
Thecolumn parameter can be either a number (0, the default, is the first column), or the column name.
For example, this fetches the names of all the books in the database, ordered by the year they were released:
$titles = $db->getAll("SELECT title FROM books ORDER BY pub_year ASC");
foreach ($titles as $title) {
echo "$title\n";
}
the Hobbit
I, Robot
Foundation
...
The getAll() method returns an array of all the rows returned by the query:
$all = $db->getAll(SQL [, values [, fetchmode ]]);
For example, the following code builds a select box containing the names of the movies. The ID of the selected movie is submitted as the parameter value.
$results = $db->getAll("SELECT bookid,title FROM books ORDER BY pub_year ASC");
echo "<select name='movie'>\n";
foreach ($results as $result) {
echo "<option value={$result[0]}>{$result[1]}</option>\n";
}
echo "</select>";
All theget*()methods returnDB_ERRORwhen an error occurs.
Next: Details About a Query Response >>
More PHP Articles
More By O'Reilly Media
|
This article is excerpted from chapter eight of the book Programming PHP, Second Edition, written by Kevin Tatroe, Rasmus Lerdorf, and Peter MacIntyre (O'Reilly, 2006; ISBN: 0596006810). Check it out today at your favorite bookstore. Buy this book now.
|
|