hairynuggets hairynuggets - 5 months ago 25
SQL Question

Codeigniter - Perform action if database query returns no results

How can I return a value of 'no data found' if my query returns no results???

This is my code:

function getTerms($letter) {


$this->db->select('term, definition');
$this->db->from('glossary');
$this->db->where(array('letter' => $letter));

$query = $this->db->get();

foreach ($query->result() as $row) {
$data[] = array(
'term' => $row->term,
'definition' => $row->definition
);
}

return $data;
}


It currently returns the $data variable even if the query returns no results which is giving me php errors. How can I check that there are results before returning the $data array.

Answer

It currently returns the $data variable even if the query returns no results which is giving me php errors.

It's a good habit to initialize the array that you intend to build:

$data = array();
// Loop through possible results, adding to $data

If there are no results you'll get an empty array returned, then check that in your controller.

This way, at least the variable is defined and you won't get notices.