You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter报错:在布尔值上调用num_rows()方法,求解决方案

错误分析与解决

核心错误原因

错误Call to a member function num_rows() on bool出现在cart_data.php第2行,说明传递到视图的$cart变量不是有效的数据库查询结果对象,而是布尔值false。根源是模型Sale_m的get_cart方法中表名写错:代码里用了$this->db->from('cart');,但实际购物车表名为t_cart(从add_cart方法的插入操作、查询最大cart_id的SQL可确认),表名不匹配导致查询失败,返回false。

修复步骤

1. 修正模型Sale_m.php的get_cart方法

将表名从cart改为t_cart:

public function get_cart($params = null)
{
    $this->db->select('*, p_item.name as item_name, t_cart.price as cart_price');
    $this->db->from('t_cart'); // 修正为正确的表名t_cart
    $this->db->join('p_item', 't_cart.item_id = p_item.item_id');
    if($params != null) {
        $this->db->where($params);
    }
    $this->db->where('user_id', $this->session->userdata('userid'));
    $query = $this->db->get();
    return $query;
}

2. 修复视图cart_data.php的HTML语法错误

  • 按钮class错误:btn btn-xs btn primary改为btn btn-xs btn-primary
  • 空购物车提示的HTML错误:<td colspan="8"> class="text-center">改为<td colspan="8" class="text-center">

修正后的cart_data.php代码:

<?php $no = 1;
if($cart->num_rows() > 0) {
    foreach ($cart->result() as $c =>$data) { ?>
        <tr>
            <td><?=$no++?>.</td>
            <td><?=$data->barcode?></td>
            <td><?=$data->item_name?></td>
            <td class="text-right"><?=$data->cart_price?></td>
            <td class="text-center"><?=$data->qty?></td>
            <td class="text-right"><?=$data->discount_item?></td>
            <td class="text-right"id="total"><?=$data->total?></td>
            <td class="text-center" width="160px">
            <button id="update_cart" data-toggle="modal" data-target="#modal-item-edit"
            data-cartid="<?=$data->cart_id?>"
            data-barcode="<?=$data->barcode?>"
            data-product="<?=$data->item_name?>"
            data-price="<?=$data->cart_price?>"
            data-qty="<?=$data->qty?>"
            data-discount="<?=$data->discount_item?>"
            data-total="<?=$data->total?>"
            class="btn btn-xs btn-primary">
            <i class="fa fa-pencil"></i> Update
            </button>
            <button id="del_cart" data-cartid="<?=$data->cart_id?>" class="btn btn-xs btn-danger">
                <i class="fa fa-trash"></i> Delete
            </button>
            </td>
        </tr>
    <?php
    }} else {
     echo '<tr>
    <td colspan="8" class="text-center">Tidak ada item</td>
    </tr>';
} ?>

3. 额外防错优化(可选)

为避免后续类似查询失败导致的视图报错,可在控制器中增加结果判断:
在Sale.php的index方法中:

$cart = $this->sale_m->get_cart();
// 若查询失败,创建空结果对象避免视图报错
if (!$cart) {
    $cart = new stdClass();
    $cart->num_rows = fn() => 0;
    $cart->result = fn() => [];
}

验证修复

完成修改后重新访问销售页面,错误将被解决:

  • 购物车查询会返回有效结果对象,num_rows()方法可正常调用
  • 视图HTML语法修复后,页面渲染正常

内容的提问来源于stack exchange,提问作者Matthew Ghani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 14:40:20