Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 614
hairynuggets Avatar asked Nov 09 '11 15:11

hairynuggets


2 Answers

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

like image 125
Colin Brock Avatar answered Sep 18 '22 00:09

Colin Brock


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.

like image 37
Wesley Murch Avatar answered Sep 18 '22 00:09

Wesley Murch