Alissa Isenberg February 2016

Fatal error: Call to a member function fetch() on boolean in index.php on line 25

I have searched this site for possible answers along with searching Google and have had no luck. I have minimal php skills and have been following a tutorial to make a php chat system on Udemy.com. I am about 1/2 way though and I get the following error. I have gone over the videos 3 times now to make sure I haven't missed anything or typed anything wrong.

I keep getting this error:

Fatal error: Call to a member function fetch() on boolean in C:\xampp\htdocs\websites\portfolio\project_examples\chat_system_AJAX_&_PHP\index.php on line 25

I assume it has something to do with this line:

<?php endwhile;?>

Here is the code for index.php

<?php
    include 'db.php';
?>

<!DOCTYPE html>

<html>

<head>
    <title>Chat System in PHP</title>

    <link rel="stylesheet" type="text/css" href="assets/css/styles.css" media="all">
</head>

<body>

<div id="container">

    <div id="chat_box">

        <?php
            $query = "SELECT * FROM portfolio_chat_system_AJAX_PHP ORDER BY id DESC";
            $run = $con->query($query);

            while($row = $run -> fetch_array()) :
        ?>

        <div id="chat_data">
            <span class="username"><?php echo $row['name']; ?></span> :
            <span class="message_text"><?php echo $row['message']; ?></span>
            <span class="message_time"><?php echo $row['date']; ?></span>
        </div>

        <?php endwhile;?>

    </div>

    <form method="post" action="index.php">
        <input type="text" name="name" placeholder="enter name here"/>
        <textarea name="enter message" placeholder="enter message here"></textarea>
        <input type="submit" name="submit" value="Send">

            

Answers


Ray February 2016

Looks like you're using mysqli. The query is failing, returning a false and assigning it to $run.

 $run = $con->query($query);

You can't call fetch_array() on a boolean primitive, it's a method of the mysqli_result class which will be returned if they query is successful.

  1. You should check to for success of query (not false) before using it as an object:

    if($run != false) {
       while($row = $run -> fetch_array())
      ...
    
  2. Fix the query that's failing. You can get detail on why it failed from the your connection object $con http://php.net/manual/en/mysqli.query.php try: echo $con->error;

Based on your comment in the OP, your query should probably be:

    $query = "SELECT * FROM chat ORDER BY id DESC";

Post Status

Asked in February 2016
Viewed 1,355 times
Voted 5
Answered 1 times

Search




Leave an answer