Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MYSQL Fatal Error: Call to a member function fetch_assoc() on boolean [duplicate]

Tags:

php

mysqli

I have been searching for about 3 hours now, and I see that a lot of people have a similar error, but I haven't found an answer on how to fix this problem yet. I see plenty of responses from people who say "your query must be returning false", but that doesn't help. I've only been using mysql and php for about a week now, so I'm very much an amateur.

I put the $count variable in there on purpose to see if my query would return the correct number of rows, and it does, but the while loop gives me the error. There are currently 2 rows in my table if that helps at all. There are also 3 total columns (id, User1, User2).

After doing a bunch of google searches on how to store multiple rows in an array, all of the responses say to use said while loop since fetch_assoc() only returns 1 row at a time.

Can someone tell me how I can fix this code, or what code I could use to load multiple rows of a mysql search into an array?

    $i = 0;
    $stmt1 = $this->conn->prepare("SELECT * FROM friends WHERE User1 = ? OR User2 = ?"); 
    $stmt1->bind_param("ss", $myuid, $myuid);

    if ($stmt1->execute()) {
        $stmt1->store_result();
        $count = $stmt1->num_rows;

        while(($row = $stmt1->get_result()->fetch_assoc()) !== FALSE){
            if ($row['User1'] == $myuid) {
                $friends[$i]= $row['User2'];
                $i++;
            } else if ($row['User2'] == $myuid){
                $friends[$i] = $row['User1'];
                $i++;
                }
        }

        $stmt1->close();
like image 200
MildewMan Avatar asked Jan 21 '26 05:01

MildewMan


1 Answers

I was able to get it to work finally. @bio_sprite - thanks for the hint of binding the results. Here is the code that I used:

    $friends = array(); 
    $i = 0;
    $stmt1 = $this->conn->prepare("SELECT User1, User2 FROM friends WHERE User1 = ? OR User2 = ?"); 
    $stmt1->bind_param("ss", $myuid, $myuid);

    if ($stmt1->execute()) {
        $stmt1->bind_result($User1, $User2);

        while($stmt1->fetch()){

            if ($User1 != $myuid) {
                $friends[$i]= $User1;
                $i++;
            } else if ($User2 != $myuid){
                $friends[$i]= $User2;
                $i++;
                }
        }

        $stmt1->close();

        return $friends;
like image 97
MildewMan Avatar answered Jan 23 '26 19:01

MildewMan