Codeigniter - perform an action if the database query returns no results

How can I return the value "no data" 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 request does not return results that give me php errors. How to check if there are results before returning the $ data array.

+6
source share
4 answers

It currently returns the $ data variable, even if the request does not return results that give me php errors.

It’s a good habit to initialize the array you are going to build:

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

If there are no results, you will get an empty array, and then check it in your controller.

Thus, at least a variable is defined, and you will not receive notifications.

+3
source

Just verify that the query returns at least one row:

 if ($query->num_rows() > 0) { // query returned results } else { // query returned no results } 

More details in the docs

+13
source

How to get the original value of an empty array for $data Just put

 $data = array(); 

before foreach

+2
source
 <?php return is_array($data) ? $data : array(); } 
+1
source

Source: https://habr.com/ru/post/901125/


All Articles