CodeIgniter Query Results

CodeIgniter Query Results function are give below.

result()

This function return query result as an array of object or an empty array in case of empty query result.Generally we use foreach loop to get value from object array.

$query = $this->db->get('employee');
//To check query produce a result set or not
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
      {
   echo $row->name;
   echo $row->salary;
       }
  }

result_array()

This function return query result as an array or an empty array in case of empty query result.

$query = $this->db->get('employee');
//To check query produce a result set or not
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
      {
   echo $row['name'];
   echo $row['salary'];
       }
  }

row()

This function return query result as an object in single result row.if query has more than one row,it return only one row.

$query = $this->db->get('employee');
//To check query produce a result set or not
if ($query->num_rows() > 0)
{
   $row = $query->row(); 
   echo $row->name;
   echo $row->salary;
}

Other Function

$query->num_rows()

This Function return number of rows by query.

$query = $this->db->get('employee'); echo $query->num_rows();

$query->num_fields()

This Function return number of FIELDS (columns) by query.

$query = $this->db->get('employee'); echo $query->num_fields();

$query->free_result()

PHP clean up everything after script execution.However,if you are running a multiple queries in a particular script you might want to free the result after each query result.

$query = $this->db->get('employee');
foreach ($query->result() as $row)
{
   echo $row->title;
}
$query->free_result(); // The $query result object will no longer be available
$query2 = $this->db->get('company');
$row = $query2->row();
echo $row->companyname;
$query2->free_result(); // The $query2 result object will no longer be available