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.
Simply check that the query returns at least one row:
if ($query->num_rows() > 0) {
// query returned results
} else {
// query returned no results
}
Read more in the docs
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With