在 <path> 中的 boolean 上调用成员函数 fetch_assoc()

2021-12-25 00:00:00 php mysqli

我在运行以下代码以显示从数据库进行的预订时遇到上述错误.

I'm getting the above error when running the below code to display bookings made from a database.

<?php
        
        $servername = "localhost";
        $username = "*********";
        $password = "********";
        $dbname = "thelibr1_fyp";


        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql = "SELECT id, tablename, numseats, person FROM confirms";
        $result = $conn->query($sql);
        ?>
                        
        <table id="Confirms" border ="2" style="length:900px;width:350px;">
              <thead>
                <tr style= "background-color: #A4A4A4;">
                  <td>Booking ID:</td>
                  <td>Table No.:</td>
                  <td>No. of Seats:</td>
                  <td>Person:</td>
                </tr>
              </thead>
            <tbody>
                <?php
                  while(($row = $result->fetch_assoc()) !== null){
                    echo
                    "<tr>
                      <td>{$row['id']}</td>
                      <td>{$row['tablename']}</td>
                      <td>{$row['numseats']}</td>
                      <td>{$row['person']}</td>
                    </tr>
";
                  }
                ?>
            </tbody>
        </table>

当我开始实时托管它时,我才开始收到错误消息.它在我的个人电脑上运行良好,数据库连接也运行良好.

I only started to receive the error when i started hosting it live. It works fine on my personal computer, the databse connection works fine also.

推荐答案

query 方法可以返回 false 而不是结果集,以防出现错误.这就是为什么您会在 fetch_assoc 方法调用中出现错误的原因,当 $result 为 false 时,这显然不存在.

The query method can return false instead of a result set in case there is an error. That is why you get the error on the fetch_assoc method call, which obviously does not exist when $result is false.

这意味着您的 SELECT 语句有错误.要显示该错误,请执行以下操作:

This means you have an error in your SELECT statement. To get that error displayed, do this:

 $result = $conn->query($sql) or die($conn->error);

很可能您对表名或列名的拼写有误.可能在移动到主机时您没有正确创建该表,并在那里拼写错误.

Most probably you have a wrong spelling for the table name or a column name. Maybe when moving to the host you did not create that table correctly, and made a spelling mistake there.

实际上,当您通过 phpAdmin 执行相同的查询时,您应该会看到相同的错误.

You should in fact see the same error when executing the same query via phpAdmin.

另外,替换这一行:

while(($row = $result->fetch_assoc()) !== null){

只要:

while($row = $result->fetch_assoc()) {

你也可以添加这个用于调试:

You could also add this for debugging:

echo "number of rows: " . $result->num_rows;

相关文章