Niklas Riecken Niklas Riecken - 6 months ago 43
PHP Question

SQL Error: Call to a member function fetch_assoc() on a non-object

I have a problem with this code:

if($sql = $this->database->query("SELECT * FROM warenkorb_artikel WHERE WarenkorbID = '".$erg['WarenkorbID']."'"))
{
while($erg = $sql->fetch_assoc()){
[...]
}

}


I am getting the error


Fatal error: Call to a member function fetch_assoc() on a non-object
in [...] on the lin where the "while($eg = $sql->fetch_assoc())" is.


Can anyone help me?

Cheers

Answer

You need to break things down so you can capture any errors you make in a query that are returned by the mysqli API.

$sql = "SELECT * 
        FROM warenkorb_artikel 
        WHERE WarenkorbID = '{$erg['WarenkorbID']}'";

$result = $this->database->query($sql);

if ( $result === false ) {
    echo $this->database->error;
    exit;
}

// do you really need a while loop, as it look like you might be
// selecting a row using a unique key?

while($row = $result->fetch_assoc()){
         [...]
}