Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

10.5. Retrieving Rows Without a Loop

Problem

You want a concise way to execute a query and retrieve the data it returns.

Solution

With PEAR DB, use DB::getRow( ) to retrieve the first (or only) row from a query:

$row = $dbh->getRow("SELECT planet,symbol FROM zodiac WHERE sign LIKE 'Pisces'");

Use DB::getAll( ) to retrieve all rows from a query:

$rows = $dbh->getAll("SELECT planet,symbol FROM zodiac WHERE element LIKE 'fire'");

Use DB::getOne( ) to retrieve just one column from one row:

$col = $dbh->getOne("SELECT symbol FROM zodiac WHERE sign = 'Libra'");

Use DB::getCol( ) to retrieve a column from all rows:

$cols = $dbh->getCol('SELECT symbol FROM zodiac');

Use DB::getAssoc( ) to retrieve all rows from a query into an associative array indexed by the first column of the query:

$assoc = $dbh->getAssoc(
    "SELECT sign,symbol,planet FROM zodiac WHERE element LIKE 'water'");

Discussion

All these functions return a DB_Error object if an error occurs in executing a query or retrieving the results. If the query returns no results, getRow( ) and getOne( ) return NULL; getAll( ), getCol( ), and getAssoc( ) return an empty array.

When returning results, getRow( ) returns an array or object, depending on the current fetch mode. The getAll( ) method returns an array of arrays or array of objects, also depending on the fetch mode. The single result getOne( ) returns is usually a string, because PHP database drivers generally cast retrieved results into strings. Similarly, getCol( ) returns ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata