大家好,我最近一直在尝试 PDO,目前正在尝试为我正在进行的项目编写一个基本数据库类。但是,我在尝试编写一个函数来使用准备好的语句执行更新查询时遇到了问题。
function update($tabledata, $table, $where){
$fields = array_keys($tabledata);
$data = array_values($tabledata);
$fieldcount = count($fields);
$wherefield = implode(array_keys($where));
$whereval = implode(array_values($where));
$this->query = "UPDATE $table SET ";
$this->query .= '(' . implode($fields, ' = ?, ') . ' = ?)';
$this->query .= " WHERE $wherefield = '$whereval'";
$this->query = $this->_clean($this->query);
$stmt = $this->conn->prepare($this->query) or die('Problem preparing query');
$stmt->execute($data)or die('Problem executing query');
}
它的使用示例是:
$usertbl = 'users';
$date = date("Y-m-d");
$updatedata = array(
'Username' => 'test',
'Password' => 'unknown',
'Email' => 'email',
);
$where = array(
'Username' => 'user'
);
$Database->update($updatedata,$usertbl,$where);
这将返回以下错误:
Warning: 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 '(Username = 'test', Password = 'unknown', Email = 'email') WHERE Username = 'use' at line 1
任何帮助将不胜感激。
最佳答案
UPDATE
查询的 SET
子句中没有括号。
http://dev.mysql.com/doc/refman/5.0/en/update.html
因此,当击中 (
时会出现语法错误。只要您尝试使用绑定(bind)参数以正确的方式执行操作,请在 WHERE
子句中执行此操作也是!
关于PHP PDO 更新准备好的语句问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4907801/