Back to Blog
Best Practice

What are returning the FETCH functions from Zend_Db

Continuing the Zend_DB article series, we are stopping now at FETCH methods that are in Zend_Db_Adapter_Abstract:
>
array  fetchAll  (string|Zend_Db_Select $sql, , )
array fetchAssoc (string|Zend_Db_Select $sql, )
array fetchCol (string|Zend_Db_Select $sql, )
string fetchOne (string|Zend_Db_Select $sql, )
array fetchPairs (string|Zend_Db_Select $sql, )
array fetchRow (string|Zend_Db_Select $sql, , )
To be more easily to follow, in green box is the classical SQL statement, and in blue box is the query written in Zend_Db style.
Lets start. Initialize the connection to our MySql database:
 style="background-color: #9FCFFF">
$db = Zend_Db::factory('Pdo_Mysql', $dbConnect);
Here is a SQL query, that we want to fetch:
 style="background-color: #B5DFC1">
$sql = "SELECT id, title FROM files";
$db->query($sql)

 style="background-color: #9FCFFF">
$select = $db->select()
             ->from('files', array('id', 'title'))
Note*: for the old style of fetching we used an old class. What you need to know is:
- query() method is similar with mysqli_query() from Mysqli PHP extension
- next_record() method is similar with mysqli_next_result() from Mysqli PHP extension
- f() method retrieve the value of the column specified as parameter
fetchAll
 style="background-color: #B5DFC1">
while($db->next_record())
{
    $a[] = array(
                 'id' => $db->f('id'),
                 'title' => $db->f('title')
                 );
}

 style="background-color: #9FCFFF">
$a = $db->fetchAll($select);

fetchAssoc
 style="background-color: #B5DFC1">
while($db->next_record())
{
    $a = array(
                             'id' => $db->f('id'),
                             'title' => $db->f('title')
                            );
}

 style="background-color: #9FCFFF">
$a = $db->fetchAssoc($select);

fetchCol
 style="background-color: #B5DFC1">
while($db->next_record())
{
    $a[] = $db->f('id');
}

 style="background-color: #9FCFFF">
$a = $db->fetchCol($select);

fetchOne
 style="background-color: #B5DFC1">
$db->next_record();
$a = $db->f('id');

 style="background-color: #9FCFFF">
$a = $db->fetchOne($select);

fetchPairs
 style="background-color: #B5DFC1">
while($db->next_record())
{
    $a = $db->f('title');
}

 style="background-color: #9FCFFF">
$a = $db->fetchPairs($select);

fetchRow
 style="background-color: #B5DFC1">
$db->next_record();
$a = array(
           'id' => $db->f('id'),
           'title' => $db->f('title')
          );

 style="background-color: #9FCFFF">
$a = $db->fetchRow($select);