【问题标题】:Call a member function bind_param() on a non-object在非对象上调用成员函数 bind_param()
【发布时间】:2015-02-02 17:58:26
【问题描述】:

我试图为用户制作可编辑的个人资料。他们点击编辑按钮(form-post)返回带有可编辑信息的页面(仅当 isset($_POST["edit"]) 在文本区域、输入和“完成编辑”按钮时。 当我单击完成编辑时。它需要启动将新信息更新到数据库的功能。但它没有更新它的返回错误:

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

我的代码:

if(isset($_POST["cedit"]) && !empty($_POST["fn"]) && !empty($_POST["ln"]) && !empty($_POST["desc"])){

    if($stmtq = $mysqli->prepare("UPDATE `sites`.`accounts` SET `fullname` = ? ,`description` = ? WHERE `id` = ? ") && !empty($_POST["fn"]) && !empty($_POST["ln"]) && !empty($_POST["desc"])){
        $stmtq->bind_param("ssd", $_POST["fn"]." ".$_POST["ln"], $_POST["desc"], $_SESSION["user_id"]);
        $stmtq->execute();
        $stmtq->close();
    }
}

【问题讨论】:

  • prepare() 之后执行print_r($stmtq);。还要检查错误日志并将error_reporting(E_ALL); 添加为脚本中的第一件事
  • Marcin the print_r($stmtq) 返回数字 1。

标签: php mysql


【解决方案1】:

您的运算符优先级存在问题,导致 $stmtq 成为 truefalse 布尔值,而不是预期的准备好的语句。

这是由于 && 条件链打包到同一个条件中。它们发生在分配= 之前。添加一些()。基本上相当于:

// $x is always assigned a boolean
if ($x = (object && true && true))

不是预期的

// $x is assigned the object
if (($x = object) && (true && true))

修复它:

// Wrap the assignment in its own () group to isolate from the && conditions
if (($stmtq = $mysqli->prepare("UPDATE `sites`.`accounts` SET `fullname` = ? ,`description` = ? WHERE `id` = ? ")) && !empty($_POST["fn"]) && !empty($_POST["ln"]) && !empty($_POST["desc"]) {
  // Successful prepare() assignment and all other conditions
  // Proceed with bind_param()/execute()
}

虽然它增加了几行,但先执行prepare() 和赋值,然后验证其他条件,或者反之亦然,这样会更容易阅读,也不容易出现这些优先级问题。

if (!empty($_POST["fn"]) && !empty($_POST["ln"]) && !empty($_POST["desc"])) {
  if ($stmtq = $mysqli->prepare(.....)) {
     // All is well, proceed with bind_param()/execute()
  }
}

有关美味的详细信息,here is PHP's operator precedence chart&& 逻辑运算符的优先级高于 = 赋值。

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 1970-01-01
    • 2011-05-28
    • 2015-10-24
    • 2013-09-26
    • 1970-01-01
    • 2013-11-19
    • 2023-04-02
    相关资源
    最近更新 更多