CodeIgniter如何统计数据库返回数组的结果数并获取首条数据
解决方案
方法一:直接统计已获取的结果数组(最简单)
既然你已经通过自定义的get_data方法拿到了所有查询结果的数组,直接用PHP内置的count()函数就能统计总数,不需要额外查询数据库,同时保留原有的首条数据获取逻辑:
$product = $this->basic->get_data('products_imported', [ 'where' => [ 'product_table' => $product_table, 'company_id' => $company_id ] ]); // 统计结果总数 $total_products = count($product); // 获取首条产品ID $first_product = isset($product[0]['id']) ? $product[0]['id'] : 'empty'; // 按要求输出 echo "count all products = {$total_products}\n"; echo "first_product = {$first_product}\n";
为什么之前num_rows报错?
因为$this->basic->get_data()返回的是普通PHP数组,而num_rows是CodeIgniter原生数据库查询结果对象(CI_DB_result)的专属方法,数组没有这个属性,所以会抛出Attempt to read property "num_rows" on array的错误。
方法二:用CI原生查询构造器(适合大数据量场景)
如果查询结果数据量很大,不想一次性加载所有数据到内存,可以用CodeIgniter的查询构造器先获取查询结果对象,再分别获取总数和首条数据:
// 构建查询条件 $this->db->where([ 'product_table' => $product_table, 'company_id' => $company_id ]); // 执行查询,获取结果对象 $query = $this->db->get('products_imported'); // 统计总数 $total_products = $query->num_rows(); // 获取首条数据(数组格式),无结果则返回null $first_product_row = $query->row_array(); $first_product = $first_product_row ? $first_product_row['id'] : 'empty'; // 按要求输出 echo "count all products = {$total_products}\n"; echo "first_product = {$first_product}\n";
关于count_all_results()的问题
你之前用的count_all_results()本质是执行了一条SELECT COUNT(*)的统计查询,只会返回总数,不会获取具体的产品数据,所以无法拿到首条ID。
内容的提问来源于stack exchange,提问作者Misha
相关产品推荐
相关产品推荐

