Codeigniter - Perform action if database query returns no results
Solution 1
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.
Solution 2
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
Solution 3
What about to give initial empty array value for $data
Just put
$data = array();
before foreach
Solution 4
<?php
return is_array($data) ? $data : array();
}
hairynuggets
Web developer/entrepeneur. Codes php, likes codeigniter, css and jquery.
Updated on June 21, 2022Comments
-
hairynuggets almost 2 years
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.