我在我的这个功能Carros_model.php
用于带来最后一次插入并在仪表板中显示它们:
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; }
它工作正常,但我发现,如果表是空的,错误
致命错误:在布尔值上调用成员函数result_array()
被扔了.我该如何解决这个问题?
在尝试获取结果之前,您应该检查查询是否有效/有任何行.如果表为空,则查询将不执行任何操作.
$query = $this->db->get(); $data = array(); if($query !== FALSE && $query->num_rows() > 0){ foreach ($query->result_array() as $row) { $data[] = $row; } } return $data;
PS没有理由使用循环$query->result_array()
,你可以返回.它已经是一排行.
$query = $this->db->get(); $data = array(); if($query !== FALSE && $query->num_rows() > 0){ $data = $query->result_array(); } return $data;