I like CodeIgniter database library alot. Infact, I use it for standalone purpose in several of my projects. One thing that distracting me is that it has an overhead while fetching result. The result_xxx method is bugging me.

We usually use codeigniter database like this

$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result_object() as $row)
{
    echo $row->title;
    echo $row->name;
    echo $row->email;
}
echo 'Total Results: ' . $query->num_rows(); 

The inner code of $query->result() inside the DB_result.php is like this

	function result_object()

	{

		if (count($this->result_object) > 0)

		{

			return $this->result_object;

		}

		

		// In the event that query caching is on the result_id variable 

		// will return FALSE since there isn't a valid SQL resource so 

		// we'll simply return an empty array.

		if ($this->result_id === FALSE OR $this->num_rows() == 0)

		{

			return array();

		}



		$this->_data_seek(0);

		while ($row = $this->_fetch_object())

		{

			$this->result_object[] = $row;

		}

		

		return $this->result_object;

	}

Notice the bold stuff, so this library buffer the result first in an inner loop, and then we could iterate the loop. This is nice, but not efficient for quick and dirty database fetching or if you use it fetching thousands rows. So I made a small modification, exposing some of its private methods.

	function _fetch_assoc() { return array(); }	

	function _fetch_object() { return array(); }

        function fetch_assoc() { return $this->_fetch_assoc(); }
        function fetch_object() { return $this->_fetch_object(); }

Sweet, now I can use the fetch_assoc and fetch_object method like this

$query = $this->db->query('SELECT name, title, email FROM my_table');
while( $row = $query->fetch_object() )
{
    echo $row->title;
    echo $row->name;
    echo $row->email;
}
echo 'Total Results: ' . $query->num_rows(); 

No more unnecessary inner loops. Actually, you can use _fetch_assoc or _fetch_object directly, but that is not nice ;)

Happy CodeIgniting everybody ;)