duanne9313 2018-06-12 05:20
浏览 49
已采纳

尝试回显注释时显示错误[重复]

I am trying to create a comment section on my website. However, my comments aren't showing because of this error

Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean in C:\xampp\htdocs\tutorials\comments.inc.php:24 Stack trace: #0 C:\xampp\htdocs\tutorials\homepage.php(23): getComments(Object(mysqli)) #1 {main} thrown in C:\xampp\htdocs\tutorials\comments.inc.php on line 24

Here is the code to comments.inc.php

<?php
include 'dbh.inc.php';

function setComments($conn) {
    if(isset($_POST['commentSubmit'])){
        $uid = $_POST['uid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', 
'$date', 
'$message')";
        $result = $conn->query($sql);

   }


}

function getComments($conn) {

    $sql = "SELECT * FROM comments";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()){
    echo "<div class='comment-box'><p>";
        echo $row['uid']."<br>";
        echo $row['date']."<br>";
        echo $row['message'];
     echo "</p></div>";

    }
}
?>

If someone could provide me with an answer that would be great and thank you in advance.

</div>
  • 写回答

1条回答 默认 最新

  • duanfen2008 2018-06-12 05:28
    关注

    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.

    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.

    You could also add this for debugging:

    echo "total rows: " . $result->num_rows;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?