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, [mixed $bind = array()], [mixed $fetchMode = null])
array fetchAssoc (string|Zend_Db_Select $sql, [mixed $bind = array()])
array fetchCol (string|Zend_Db_Select $sql, [mixed $bind = array()])
string fetchOne (string|Zend_Db_Select $sql, [mixed $bind = array()])
array fetchPairs (string|Zend_Db_Select $sql, [mixed $bind = array()])
array fetchRow (string|Zend_Db_Select $sql, [mixed $bind = array()], [mixed $fetchMode = null])
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:
$db = Zend_Db::factory('Pdo_Mysql', $dbConnect);
Here is a SQL query, that we want to fetch:
$sql = "SELECT id, title FROM files";
$db->query($sql)
$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
while($db->next_record())
{
$a[] = array(
'id' => $db->f('id'),
'title' => $db->f('title')
);
}
$a = $db->fetchAll($select);
fetchAssoc
while($db->next_record())
{
$a[$db->f('id')] = array(
'id' => $db->f('id'),
'title' => $db->f('title')
);
}
$a = $db->fetchAssoc($select);
fetchCol
while($db->next_record())
{
$a[] = $db->f('id');
}
$a = $db->fetchCol($select);
fetchOne
$db->next_record();
$a = $db->f('id');
$a = $db->fetchOne($select);
fetchPairs
while($db->next_record())
{
$a[$db->f('id')] = $db->f('title');
}
$a = $db->fetchPairs($select);
fetchRow
$db->next_record();
$a = array(
'id' => $db->f('id'),
'title' => $db->f('title')
);
$a = $db->fetchRow($select);
Looking for PHP, Laminas or Mezzio Support?
As part of the Laminas Commercial Vendor Program, Apidemia offers expert technical support and services for:
One Comment-
SQL queries using Zend_Db – SELECT » DotKernel
[…] see: – What are returning the FETCH functions from Zend_Db – Subqueries with Zend_Db – INSERT, UPDATE, DELETE statements with […]