PHP致命错误:在布尔值上调用成员函数fetch_object() [英] PHP Fatal error: Call to a member function fetch_object() on boolean

查看:106
本文介绍了PHP致命错误:在布尔值上调用成员函数fetch_object()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用php v5.6.19传输服务器后,我遇到了php致命错误,在此之前,我对以下脚本完全没有问题

I got php fatal error after transfer server with php v5.6.19, before that I had no problem at all with following script

从数据库表中获取数据:

function get_department_list($mysqli)
{
    $sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");

    if($sql->num_rows > 0){
        return $sql;
    }else{
        return false;
    }
}

以HTML格式填充数据:

<ul class="department overflow-scroll text-center">
    <?php
    $shop = new Shop;

    $depts = $shop->get_department_list($mysqli);
    while($dept = $depts->fetch_object()){
        echo '<li><a href="'.baseurl.'/shop/'.strtolower(str_replace('\'','',$dept->dept_name)).'">'.$dept->dept_name.'</a></li>';
    }
    ?>
</ul>

最后我得到一个错误:

致命错误:在第206行的C:\ xampp \ htdocs \ project \ include \ header.php中的布尔值上调用成员函数fetch_object()

Fatal error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\project\include\header.php on line 206

推荐答案

首先,您要从函数中返回一个布尔值.因此,难怪PHP会这么说.

First, you are returning a boolean from your function. So, no wonder PHP says you so.

第二,您应该分开处理.与mysqli一起使用的函数应将所有mysqli内容保留在其中.仅返回一个数组,可以在任何地方使用而无需再次调用mysqli函数.

Second, you should keep the matters separated. a function that works with mysqli should keep all mysqli stuff inside. An return just an array, that can be used anywhere without the need to call mysqli functions again.

function get_department_list($mysqli)
{
    $sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
    return $sql->fetch_all();
}

然后不使用而是foreach

And then use not while but foreach

foreach ($depts as $dept) ...

此外(还有更多可能找到这个问题的人,以寻求其问题的答案),您应该始终为mysqli设置正确的错误报告,如

Besides (and more for the people who may chance to land on this question looking for an answer to their question) you should always set proper error reporting for mysqli, like it shown in this answer

这篇关于PHP致命错误:在布尔值上调用成员函数fetch_object()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆