首页 > 解决方案 > 我在 codeigniter 中收到不支持的操作数类型错误

问题描述

当我尝试添加分页链接时,出现不支持的操作数类型错误

这是我的代码

模型

public function getCategory($limit,$offset){

    $this->db->select("*");
    $this->db->from("tbl_category");
    $this->db->limit($limit,$offset);

    $row = $this->db->get()->result_array();

    return $row;
}

public function num_rows(){
    $this->db->select('*');
    $this->db->from('tbl_category');
    $row = $this->db->get()->result_array();
    return $row;
}

控制器

public function category($script="list",$id=""){
    $data['script'] = $script;

    if($script == 'list'){

        $config = [
            'base_url' => base_url('http://localhost/training/admin/'),
            'per_page' => 2,
            'total_rows' => $this->admin_model->num_rows(),
        ];
        $this->pagination->initialize($config);
        $rows = $this->admin_model->getCategory($config['per_page'], $this->uri->segment(3));
        $data['rows'] = $rows;
    }

在我的视图文件中,我这样做是为了获取链接

<?php $this->pagination->create_links(); ?>

我得到的错误如下

遇到未捕获的异常类型:错误

消息:不支持的操作数类型

文件名:C:\xampp\htdocs\training\system\libraries\Pagination.php

行号:412

回溯:

文件:C:\xampp\htdocs\training\application\views\category.php 行:101 功能:create_links

文件:C:\xampp\htdocs\training\application\controllers\Admin.php 行:150 功能:查看

文件:C:\xampp\htdocs\training\index.php 行:315 功能:require_once

标签: phpcodeigniter

解决方案


在您的控制器函数中,当您获得结果时,您必须将其传递给您的视图文件,如下所示。

$data['rows'] = $rows;

// load the view
$this->load->view('category_view', $data);

然后在您的视图文件中,您可以获得分页链接。

<?php echo $this->pagination->create_links(); ?>

编辑 =>在配置数组'total_rows' => $this->admin_model->num_rows(),中,您分配的是数组而不是计数。

您的模型功能是

public function num_rows(){
    $this->db->select('*');
    $this->db->from('tbl_category');
    $row = $this->db->get()->result_array();
    return $row; //This $row is an Array, NOT count no. of rows
}

在上面的函数中,您返回return $row;的是一个数组。这就是您收到诸如 Unsupported operand types error 之类的错误的原因

所以有2个解决方案。只尝试任何一种解决方案。

要么 1)您必须将结果集的计数返回给 total_rows 变量:

$config = [
            'base_url' => base_url('http://localhost/training/admin/'),
            'per_page' => 2,
            'total_rows' => count($this->admin_model->num_rows()), //Pass the count of returned array.
        ];

或 2)您可以更改功能。

public function num_rows(){
    $this->db->select('*');
    $this->db->from('tbl_category');
    $row = $this->db->get()->result_array();
    return $row->num_rows(); //Return count result instead of array.
}

注意:-如果您只想计算行数,您可以使用$this->db->count_all_results()如下。

public function num_rows(){
    $this->db->from('tbl_category');
    return $this->db->count_all_results();
}

num_rows() :- 使用num_rows()你首先执行查询,然后你可以检查你得到了多少行。当您需要表格数据时很有用

count_all_results() :- 使用count_all_results()您可以获得查询将产生的行数,但不会给您实际的结果集。当您只需要行数时很有用,即分页,显示编号。记录等

在这里参考我的另一个答案。 Codigniter 查询返回错误的计数


推荐阅读