如果表为空,CodeIgniter result_array()出现布尔错误 [英] CodeIgniter result_array() on boolean error if the table is empty
问题描述
我的 Carros_model.php
中具有此功能,用于引入最后的插入并将其显示在仪表板中:
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
致命错误:在布尔值上调用成员函数result_array()
Fatal error: Call to a member function result_array() on boolean
被抛出。我该如何解决呢?
is thrown. How do I solve this?
推荐答案
您应该先检查查询是否工作/是否有任何行,然后再尝试获取它结果。如果表为空,则查询将不执行任何操作。
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。没有理由在 $ query-> result_array()
上使用循环,只需返回即可。
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;
这篇关于如果表为空,CodeIgniter result_array()出现布尔错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!