-2

Why is this code not working? I'm met with the "called to member function fetch_assoc() on a non-object" error when PHP gets to this point.

                $result = $db->query("SELECT * FROM users");
                while ($row = $result->fetch_assoc()) {
                    print_r($row);
                    // echo "<tr><td>" . $row["username"] . "</td> <td>" . $row["wins"] . "</td> <td>" . $row["losses"] . "</td></tr>\n";
                }

I can include additional information, but this is all I thought to be relevant.

2
  • 1
    Because $db->query failed.
    – Musa
    Feb 21, 2013 at 18:11
  • 1
    You sure you didn't get an entire list of possible duplicate questions when you typed in the title of your question?
    – PeeHaa
    Feb 21, 2013 at 18:13

2 Answers 2

1

Basically, $result isn't an object. Check if the SQL query returns results and if $result should be a php object.

3
  • But in the PHP manual they use the fetch_assoc() function the exact same way I do. php.net/manual/en/mysqli-result.fetch-assoc.php
    – Doug Smith
    Feb 21, 2013 at 18:13
  • @Doug No, you may notice that they do error checking on the result of the query in the manual.
    – deceze
    Feb 21, 2013 at 18:15
  • Exactly, you should check if $result is what you expect before doing the while loop.
    – agarassino
    Feb 21, 2013 at 18:28
0

What do you using? MySQLi? If yes after $db->query() to write:

if(!$result)
    echo $db->error;
else
{
    while ($row = $result->fetch_assoc()) {
        print_r($row);
        // echo "<tr><td>" . $row["username"] . "</td> <td>" . $row["wins"] . "</td> <td>" . $row["losses"] . "</td></tr>\n";
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.