Counting the number of results returned by a database query in Codeigniter

后端 未结 6 1798
无人及你
无人及你 2021-01-12 15:53

I am not having much luck detecting when a database query in Codeigniter returns zero results. I have had a good read of the notes on the PHP count function but am none the

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 16:08

    The best thing to do in your model is the following:

    $query = $this->db->something()....
    ...
    ...
    if ( $query->num_rows() > 0 )
    {
        return $query->result();
    }
    else
    {
        return FALSE;
    }
    

    Then in your controller or view you would do the following:

    if ( !empty($my_db_result) ) 
    {
        ......
    }
    

    This process enables you to respond on the result based on the result type. If the rows could be retrieved this will return an array of which the items can be counted by PHP's count() function. Since the second block checks if the result is empty (note that "FALSE" is treated as being empty) you won't bump into any issues (e.g. when using a foreach loop) and you can specify what to do in case there were no results.

提交回复
热议问题