duanhuo7441 2016-03-22 06:45
浏览 117

PHP致命错误:在布尔值上调用成员函数fetch_object()

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

Fetch data from db table:

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;
    }
}

Populate data in 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>

In the end I got an error:

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

  • 写回答

2条回答 默认 最新

  • duansha6410 2016-03-22 06:55
    关注

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

    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();
    }
    

    And then use not while but foreach

    foreach ($depts as $dept) ...
    

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100