PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 10.6 Retrieving Rows Without a Loop

10.6.1 Problem

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

10.6.2 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'");

10.6.3 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 an array of results whose values are usually strings. The results from getAssoc( ) are returned as an array. The type of elements of that array are controlled by the fetch mode.

Like DB::query( ), you can pass these functions a query with placeholders in it and an array of parameters to fill the placeholders. The parameters are properly quoted when they replace the placeholders in the query:

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

The parameter array is the second argument to each of these functions, except getCol( ) and getAssoc( ). For these two functions, the parameter array is the third argument. The second argument to getCol( ) is a column number to return if you don't want the first column (column number 0). For example, this returns the values of the planet column:

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

The second argument to getAssoc( ) is a boolean that tells the function whether to force the values in the associative array it returns to be arrays themselves even if they could be scalars. Take this query for example:

$assoc = $dbh->getAssoc(
    "SELECT sign,symbol FROM zodiac WHERE element LIKE 'water'");
print_r($assoc);
Array
(
    [Cancer] => Crab
    [Scorpio] => Scorpion
    [Pisces] => Fishes
)

Because the query passed to getAssoc( ) asks only for two columns, the first column is the array key, and the second column is the scalar array value. Here's how to force the array values to be one-element arrays:

$assoc = $dbh->getAssoc(
    "SELECT sign,symbol FROM zodiac WHERE element LIKE 'water'",true);
print_r($assoc);
Array
(
    [Cancer] => Array
        (
            [0] => Crab
        )
    [Scorpio] => Array
        (
            [0] => Scorpion
        )
    [Pisces] => Array
        (
            [0] => Fishes
        )
)

Just as fetchRow( ) and fetchInto( ) do, getRow( ), getAssoc( ), and getAll( ) put data in numeric arrays by default. You can pass them a fetch mode (the third argument to getRow( ) or getAll( ), the fourth argument to getAssoc( )). They also respect the fetch mode set by DB::setFetchMode( ).

10.6.4 See Also

Recipe 10.5 for more on the fetch mode; documentation on fetching at http://pear.php.net/manual/en/core.db.tut_fetch.php, DB::getRow( ) at http://pear.php.net/manual/en/core.db.getrow.php, DB::getAll( ) at http://pear.php.net/manual/en/core.db.getall.php, DB::getOne( ) at http://pear.php.net/manual/en/core.db.getone.php, DB::getCol( ) at http://pear.php.net/manual/en/core.db.getcol.php, and DB::getAssoc( ) at http://pear.php.net/manual/en/core.db.getassoc.php.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    10.1 Introduction
    Recipe 10.2 Using Text-File Databases
    Recipe 10.3 Using DBM Databases
    Recipe 10.4 Connecting to a SQL Database
    Recipe 10.5 Querying a SQL Database
    Recipe 10.6 Retrieving Rows Without a Loop
    Recipe 10.7 Modifying Data in a SQL Database
    Recipe 10.8 Repeating Queries Efficiently
    Recipe 10.9 Finding the Number of Rows Returned by a Query
    Recipe 10.10 Escaping Quotes
    Recipe 10.11 Logging Debugging Information and Errors
    Recipe 10.12 Assigning Unique ID Values Automatically
    Recipe 10.13 Building Queries Programmatically
    Recipe 10.14 Making Paginated Links for a Series of Records
    Recipe 10.15 Caching Queries and Results
    Recipe 10.16 Program: Storing a Threaded Message Board
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele