繁体   English   中英

调用mysqli查询中的成员函数错误

[英]Call to a member function error in mysqli query

将if && in_array($itemID, $userItemIDS)到if语句后,下面的方法返回错误。

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;
    }

因为$q将等于&&运算符之间的布尔结果

  • 您的数据库对象对象(如果成功,则视为正数
  • in_array函数(在所有情况下都是布尔值)

你需要括号分配:

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;
}

我会分开prepare和第一次检查的电话,以确保呼叫成功:

$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;
}

这也将使您的代码更易于阅读和维护。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM