【问题标题】:Why it says Boolean was given为什么它说 Boolean is given
【发布时间】:2016-09-27 02:42:21
【问题描述】:

谁能帮我解决这个问题。我正在尝试从表中获取所有数据。但它一直以布尔值返回。

<?php
    $con = mysqli_connect("localhost", "root", "", "student");

    $query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC";

    $result = mysqli_query($con, $query);

    while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
    }

    echo json_encode($data);
?>

给出的错误是:

> Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
> boolean given in D:\Xampp\htdocs\student\announcement.php on line 8
> 
> Notice: Undefined variable: data in
> D:\Xampp\htdocs\student\announcement.php on line 12 null

【问题讨论】:

标签: php json database boolean


【解决方案1】:

因为 mysqli_query 返回 false,$result 包含 bool(false),而 mysqli_fetch_assoc 需要一个 mysqli_result 对象,当你给它一个 bool 时它会抱怨。我们不知道为什么 mysqli_query 返回 false,并且由于您没有启用错误报告,PHP 不会告诉您原因。你需要在你的代码中进行错误检查以更早地捕捉到这一点,并让 php 告诉你出了什么问题。最简单的方法:用

开始你的脚本
<?php
error_reporting(E_ALL);
if(!mysqli_report(MYSQLI_REPORT_ALL)){
throw new RuntimeException("unable to set mysqli_report to MYSQLI_REPORT_ALL !");
}

我还建议运行一个将错误转换为异常的错误处理程序,像这样

function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

现在php应该在发生错误时给出详细的报告,包括为什么你的mysqli_query返回false。

【讨论】:

    【解决方案2】:

    请确保“公告”表中有数据。

    您可以使用 mysqli_num_rows() 函数检查结果集中返回的行数。

    试试这个:

    $con = mysqli_connect("localhost", "root", "", "student");
    $query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC";
    $result = mysqli_query($con, $query);
    
    $rowcount = mysqli_num_rows($result); //returns number of rows
    
    if($rowcount > 0) {
      while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
      }
      echo json_encode($data);
    }
    

    如有任何疑问/疑虑,请告知我们。

    【讨论】:

    • 他的问题是查询错误或者连接错误不是空表
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2011-12-22
    • 2020-05-03
    • 1970-01-01
    • 2012-12-02
    相关资源
    最近更新 更多