Codeigniter - 从数据库中计算数组,

问题描述 投票:0回答:1

我有这个代码:

$product = $this->basic->get_data('products_imported',array('where'=>array('product_table'=>$product_table,'company_id' =>$company_id)));

如你所见,结果是一个 array() 所以如果我想获取第一个结果我必须使用这个:

$first_product = isset($product [0]['id']) ? $product [0]['id'] : 'empty';  

我的问题是:我如何计算所有结果? 我必须输出这样的结果:
计算所有产品 = 10 // 例如
first_product = 3 // 产品 ID
我尝试了 num_rows 但出现此错误

Message: Attempt to read property "num_rows" on array

也尝试过这样:

$this->db->select('id');
$this->db->from('products_imported');
$this->db->where(['product_table' => $product_table, 'company_id'=>$company_id]);
$products_counter = $this->db->count_all_results();

对于这段代码,我可以计算结果,但我无法像第一个代码中那样获取第一个产品
你能帮我吗
提前致谢

尝试了很多方法,返回错误

codeigniter
1个回答
0
投票

您无法获取第一行,因为您还没有获取任何内容。 您正在使用

$this->db->count_all_results()
,它不返回对象。 这也是
$this->db->num_rows();
在计数为零后不返回任何结果的原因。

改变

$products_counter = $this->db->count_all_results();

$query = $this->db->get();
$product = $query->result_array();
$products_counter = count($product);

您也得到了您正在寻找的

$product[0]['id']

© www.soinside.com 2019 - 2024. All rights reserved.