0

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

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

这是我的真实代码。

4

4 回答 4

3

删除 col3=? 之后的“,”

这将修复语法错误

于 2013-10-28T23:28:35.943 回答
1
 $this->query = "UPDATE users SET col1=?, col2=?, col3=?, WHERE username='$username'";

您有一个额外的逗号,这意味着您的 SQL 正在将“WHERE”作为另一列读取,并且一切都搞砸了。

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

应该可以正常工作。

针对下面的评论,这是正确的处理方法,所以它一定是某个地方的错误变量,你得到什么错误消息?(如果有)

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

于 2013-10-28T23:28:39.430 回答
0

Is it possible to update more than one table columns in one go

Yes. Actually, updating many fields in one query is a very core feature of any DBMS. You can always expect it to be supported.

I tried this but in-vain.

Well, you have to try more, like we all do. After all, it's your job.

Two notes regarding your "real" code:

  1. You have to bind ALL variables in the query, not only some of them
  2. you have to configure mysqli to report errors:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
于 2013-10-28T23:49:59.973 回答
0

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

在php中更新一行mysql

于 2013-10-28T23:31:01.347 回答