Quick PEAR::DB calls

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Query information >>

Previous chapter: PEAR::DB

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.