Mysql查询更新多列错误

时间:2013-01-16 23:19:22

标签: php mysql sql-update

我正在尝试使用此代码一次上传多个列:

    function updateMultiple($idElement,$arrayFieldValues=""){

        $toSave=$arrayFieldValues?$arrayFieldValues:$_POST;

        foreach($toSave as $field => $value) {
                    if (strpos($field, 'save_') === 0) {
                        $field = str_replace('save_', '', $field);
                        $updateString .= $field."='".addslashes($value)."', ";
                    }
                }
        $updateString = substr_replace($updateString ,"",-2);

       $query="UPDATE ".$this->tab."
            SET ".$updateString.", lastUser='".$usrId."'
            WHERE ".$colName." = '".$idElement."'";
            $this->execute($query);
   }

但是我收到了这个错误:

PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET Country='England', FirstName='John', LastName='Smith', lastUser='10' ' at line 2

但对我来说这一切似乎都是对的!

4 个答案:

答案 0 :(得分:1)

根据蒂姆的回答,你应该使用Prepared Statements。查看documentation示例和进一步的文档。总之,而不是$query="UPDATE ".$this->tab." SET ".$updateString.", lastUser='".$usrId."' WHERE ".$colName." = '".$idElement."'";使用:

$query = 'UPDATE '.$this->tab.' SET lastUser = :user WHERE '.$colName.' = :colvalue'; 
$pdo->execute(array(:user => $usrId, :colvalue => $idElement));

您可能还想使用交易,但这是留给读者的练习。

答案 1 :(得分:0)

你错过了一个。在UPDATE和SET之间。 嗯,也许吧。在任何情况下,发送到PDO的SQL都是错误的。它缺少UPDATE关键字。 检查评论。

答案 2 :(得分:0)

您需要为sql语句中的每一列提供一个值。 试试这段代码:

$query="UPDATE ".$this->tab." SET ".$updateString."='yourString' , lastUser='".$usrId."'
        WHERE ".$colName." = '".$idElement."'";

答案 3 :(得分:0)

试试这个

$query="UPDATE news SET title='$title', date='$date', body='$body' WHERE newsID=$ID 
相关问题