使用单个 MySQL 语句查询更新 MySQL 数据库表字段


update mysql database table fields with a single mysqli statement query

我有一个数据库表,我正在以这种方式更新表列。

    $mysqli = new mysqli('localhost', 'root', '', 'db');
        if (mysqli_connect_errno()) {
            echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
            return 'error';
        }
   $username = $data['username'];
   $data['image'] = $this->replace_whitespace($data['image']);
   foreach($data as $key=>$value){
       $this->query = "UPDATE users SET $key=? WHERE username='$username'";
       $this->statement = $mysqli->prepare($this->query);
       if($this->statement){
           $this->statement->bind_param('s', $value);
           $this->statement->execute();
           $this->statement->close();
       }
   }

是否可以一次更新多个表列。我试过这个,但徒劳无功。

   $this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
   $this->statement = $mysqli->prepare($this->query);
   if($this->statement){
       $this->statement->bind_param('sss', $value1, $value2, $value3);
       $this->statement->execute();
       $this->statement->close();
   }

有没有更好的方法?

        $mysqli = new mysqli('localhost', 'root', '', 'db');
        if (mysqli_connect_errno()) {
            echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
            return 'error';
        }
        $username = $data['username'];
        $this->query = "UPDATE users SET fname=?, lname=?, email=?, tpin=?, image=?, address=? country=?, city=?, state=?, postal=? WHERE username='$username'";
        $this->statement = $mysqli->prepare($this->query);
        if ($this->statement) {
            $this->statement->bind_param('ssssssssss', $data['fname'],$data['lname'],$data['email'],$data['tpin'], $data['file'], $data['address'],$data['country'],$data['city'],$data['state'], $data['post_code']);
            $this->statement->execute();
             $this->statement->close();
       }

这是我的真实代码。

删除 col3= 后面的 ","?

这将修复语法错误

 $this->query = "UPDATE users SET col1=?, col2=?, col3=?, WHERE username='$username'";

你有一个额外的逗号,这意味着你的SQL将"WHERE"读作另一列,一切都搞砸了。

 $this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";

应该工作正常。

作为对下面评论的回应,这是正确的解决方法,因此它一定是某处的错误变量,您收到什么错误消息?(如有)

也可能是您要绑定的参数之一不是字符串。无论如何,我们需要一个更深入的例子。

是否可以一次更新多个表列

是的。实际上,在一个查询中更新许多字段是任何DBMS的核心功能。您始终可以期望它得到支持。

我试过这个,但徒劳无功。

好吧,你必须尝试更多,就像我们所有人一样。毕竟,这是你的工作。

关于您的"真实"代码的两个注意事项:

  1. 您必须绑定查询中的所有变量,而不仅仅是其中一些变量
  2. 您必须配置 MySQLi 以报告错误:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

我认为它的工作方式与将新值放入数据库的方式相同。

在 php 中更新一行 mysql