CodeIgniter result_array() on boolean error if the

2019-07-09 04:57发布

问题:

I have this function in my Carros_model.php that is used to bring the last insertions and display them in the dashboard:

public function select_all($limit = 3)
{
    $this->db
        ->select('marca.nome_marca,'
               . 'combustivel.nome_combustivel,'
               . 'cambio.descricao_cambio,'
               . 'DATE_FORMAT(carro.data_criacao, "%d/%m/%Y") as criacao,'
               . 'DATE_FORMAT(carro.data_modificacao, "%d/%m/%Y") as modificacao,'
               . 'carro.*')
        ->from('carro')
        ->join('marca', 'marca.id = carro.id_marca')
        ->join('combustivel', 'combustivel.id = carro.id_combustivel')
        ->join('cambio', 'cambio.id = carro.id_cambio')
        ->order_by('carro.id', 'DESC')
        ->limit($limit, 0);

    $query = $this->db->get();

    foreach ($query->result_array() as $row) {
        $data[] = $row;
    }

    $query->free_result();

    return $data;
}

It works fine, but I discovered that if the table is empty, the error

Fatal error: Call to a member function result_array() on boolean

is thrown. How do I solve this?

回答1:

You should be checking to see if the query worked/has any rows before trying to get its results. If the table is empty, then the query won't do anything.

$query = $this->db->get();

$data = array();
if($query !== FALSE && $query->num_rows() > 0){
    foreach ($query->result_array() as $row) {
        $data[] = $row;
    }
}

return $data;

P.S. There's no reason to use a loop over $query->result_array(), you can just return that. It's already an array of rows.

$query = $this->db->get();

$data = array();
if($query !== FALSE && $query->num_rows() > 0){
    $data = $query->result_array();
}

return $data;


回答2:

Make this change in your code (Add $data array after the $query):

$query = $this->db->get();
$data = Array();
foreach ($query->result_array() as $row) {
    $data[] = $row;
}

This happens because $data variable doesn't exist unless you create an empty variable before the loop in case there are no results.