在非对象上调用成员函数bind_param()

jes*_*man 2 php mysql

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

Call to a member function bind_param() on a non-object
Run Code Online (Sandbox Code Playgroud)

我的代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 5

运算符优先级导致$stmtqtruefalse布尔值而不是预期的预处理语句存在问题.

这是由于&&条件链包含在相同的条件中.它们发生在任务之前=.添加一些().基本上它相当于:

// $x is always assigned a boolean
if ($x = (object && true && true))
Run Code Online (Sandbox Code Playgroud)

而不是预期的

// $x is assigned the object
if (($x = object) && (true && true))
Run Code Online (Sandbox Code Playgroud)

要解决这个问题:

// 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()
}
Run Code Online (Sandbox Code Playgroud)

虽然它增加了几行,但它更容易阅读并且更不容易出现这些优先级问题,prepare()首先进行分配,然后验证其他条件,反之亦然.

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

有关美味的详细信息,这里是PHP的运算符优先级图表.该&&逻辑操作符比一个更高的优先级=分配.