Fetching Rows With Zend_Db fetch()


What is really handy in Zend Framework is that you can fetch the entire row set with the fetchAll() method. It comes with some parameters that you can use for limiting the result or ordering, but in general you can use it without specifying parameters. Let say this is the model:

<?php
class User extends Zend_Db_Table
{
 
	public function listAll()
	{
		$query = "SELECT * FROM user";
 
		// exec query
		$rs = $this->getAdapter()->query($query);
 
		return $rs->fetchAll();
 
	}
 
}

You can simply return the row set with the fetchAll() method as described in the example, but what if you have to loop through the rows and to modify somehow the values?

Fetching a Row

By simply change the code like so:

class User extends Zend_Db_Table
{
 
	public function listAll()
	{
		$query = "SELECT * FROM user";
 
		// exec query
		$rs = $this->getAdapter()->query($query);
 
		// fetch
		$list = array();
		while ($row = $rs->fetch()) {
			// removing the password column value
			$row['password'] = '';
 
		    $list[] = $row;
		}
 
		return $list;
	}
}

you can modify the rows and you’ll have the same result.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s