Call to a member function error in mysqli query

66 views Asked by At

The below method is returning an error after I added && in_array($itemID, $userItemIDS) to the if statement.

Fatal error: Call to a member function bind_param() on a non-object

    /**
    * Deactivate item.
    *
    * @param (int) $itemID - Variable representing an item's id.
    */
    public function deactivate($itemID) {

        //get user item ids
        $userItemIDS = $this->helperClass->userItemIDS();

        if( $q = $this->db->mysqli->prepare("UPDATE items SET active = 0 WHERE id = ?") && in_array($itemID, $userItemIDS) )
        {
            $q->bind_param("i", $itemID);
            $q->execute();
            $q->close();
            return true;
        }
            return false;
    }
2

There are 2 answers

1
Tim Biegeleisen On BEST ANSWER

I would separate out the call to prepare and first check to make sure that the call succeeded:

$q = $this->db->mysqli->prepare("UPDATE items SET active = 0 WHERE id = ?");

if ($q != FALSE && in_array($itemID, $userItemIDS)) {
    $q->bind_param("i", $itemID);
    $q->execute();
    $q->close();
    return true;
}

This will also make your code easier to read and maintain.

1
sdespont On

Because $q will equal the boolean result of the && operator between

  • your DB object object (considered positive if success)
  • the in_array function (boolean in all cases)

you need to bracket the assignment:

public function deactivate($itemID) {

    //get user item ids
    $userItemIDS = $this->helperClass->userItemIDS();

    if( ($q = $this->db->mysqli->prepare("UPDATE items SET active = 0 WHERE id = ?")) 
              && in_array($itemID, $userItemIDS) ) {
        $q->bind_param("i", $itemID);
        $q->execute();
        $q->close();
        return true;
    }
    return false;
}