Codeigniter select query types

Here is three select query types for select one row, select one field value and select multiple rows using Codeigniter Active Record.

Codeigniter select query types

  1. Select one row using Codeigniter Active Record
  2. Select one field value using Codeigniter Active Record
  3. Select multiple rows using Codeigniter Active Record
Codeigniter select query types
Codeigniter select query types

1. Select one row using Codeigniter Active Record

If record found for given condition code returns stdClass Object row and if no record found for given condition code returns blank array.

$row = $this->db->get_where('table_name', array('field_name' => $fieldValue))->row();

2. Select one field value using Codeigniter Active Record

If record found for given condition code returns and if no record found for given condition PHP Notice generate.

Below practice only recommended if we confirm that our query condition will match in table and return row. If no row match from table PHP generate “Severity: Notice – Trying to get property of non-object” as we trying to access property direct of return result object.

$fieldVal = $this->db->select('select_field_name')
                  ->get_where('table_name', array('condition_field_name' => $fieldValue))
                  ->row()
                  ->select_field_name;

3. Select multiple rows using Codeigniter Active Record

//FOR GET ONE ROW
$this->db->select('field_name1, field_name2');
$this->db->where('condition_field_name', $fieldValue);
$this->db->from('table_name');
$res = $this->db->get();
if($res->num_rows > 0)
{
	$res = $res->result();
	$row = $res[0];
}

//FOR MULTIPLE ROW
$this->db->select('field_name1, field_name2');
$this->db->where('condition_field_name', $fieldValue);
$this->db->from('table_name');
$res = $this->db->get();
if($res->num_rows > 0)
{
	$rows = $res->result();
	foreach($rows as $row)
	{
		echo $row->field_name1;
		echo $row->field_name2;
	}
}

For more advanced and useful example: Active Record