SQL 更新语法错误
SQL Syntax Error with update
我正在尝试为用户设置设置的方式,我在数据库中以 json 格式保存设置。当我尝试更新用户时出现语法错误:
Warning: 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 MariaDB server version for the right
syntax to use near ''settings' = '{\"background-color\":\"050505\"}'
WHERE ID
= '2'' at line 1 in
C:...\htdocs\app\model\model.database.php on line 29
这是我的代码。
public function setColor(){
$modUser = $this->model('user');
$modInput = $this->model('input');
$modViewData = $this->model('viewData');
$modUser->setSetting("background-color",str_replace('#', "", $modInput->returnPost("color")));
$this->view('profile/view.profile', $modViewData->getData());
}
//in User model
public function setSetting($name, $value){
$settings = $this->getSetting();
$settings[$name] = $value;
$settings = json_encode($settings);
$this->update("settings", $settings);
}
public function update($field, $value){
$sql = "UPDATE `users` SET :field = :value WHERE `ID` = :id";
$params = [":field" => $field, ":value" => $value, ":id" => $this->_data->ID];
$database = $this->model('database');
$database->query($sql,$params);
}
您不能参数化 table 和列名。您需要将它们直接插入到查询字符串中。一种方法是:
$sql = "UPDATE `users` SET $field = :value WHERE `ID` = :id";
我正在尝试为用户设置设置的方式,我在数据库中以 json 格式保存设置。当我尝试更新用户时出现语法错误:
Warning: 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 MariaDB server version for the right syntax to use near ''settings' = '{\"background-color\":\"050505\"}' WHERE
ID
= '2'' at line 1 in C:...\htdocs\app\model\model.database.php on line 29
这是我的代码。
public function setColor(){
$modUser = $this->model('user');
$modInput = $this->model('input');
$modViewData = $this->model('viewData');
$modUser->setSetting("background-color",str_replace('#', "", $modInput->returnPost("color")));
$this->view('profile/view.profile', $modViewData->getData());
}
//in User model
public function setSetting($name, $value){
$settings = $this->getSetting();
$settings[$name] = $value;
$settings = json_encode($settings);
$this->update("settings", $settings);
}
public function update($field, $value){
$sql = "UPDATE `users` SET :field = :value WHERE `ID` = :id";
$params = [":field" => $field, ":value" => $value, ":id" => $this->_data->ID];
$database = $this->model('database');
$database->query($sql,$params);
}
您不能参数化 table 和列名。您需要将它们直接插入到查询字符串中。一种方法是:
$sql = "UPDATE `users` SET $field = :value WHERE `ID` = :id";