【发布时间】:2021-01-10 15:07:42
【问题描述】:
我正在尝试修补我的数据库中的一个值,但出现错误。
后端:
router.patch("/toggleState", (req, res) => {
const todoId = req.body.todoId;
const attribute = req.body.attribute;
const newValue = req.body.newValue;
const sql = "UPDATE posts SET ? = ? WHERE todo_id = ?";
db.query(sql, [attribute, newValue, todoId], (err, result) => {
if (err) throw err;
res.send(result);
});
});
前端:
const toggleState = (todo_id, attribute, newValue) => {
if (userId) {
console.log("ATTRIBUTE: ", attribute);
//Axios.patch(`${apiUrl}/todo/toggleState`, { todoId: todo_id, attribute: attribute, newValue: newValue });
}
dispatch({ type: actionTypes.toggleState, payload: { todo_id, attribute } });
};
错误:“您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,了解在 ''important' = 1 WHERE todo_id = 1' 附近使用的正确语法在第 1 行"
处理后的 SQL: sql: "UPDATE posts SET 'important' = 1 WHERE todo_id = 1"
我注意到我的属性变量(重要)周围有 ' ' 撇号,我认为这是导致错误的原因。悬停我检查了前端和后端的变量,当我 console.log 时没有撇号,变量是 typeof 字符串。有什么想法吗?
此外,当我在 mysql-workbench 中尝试相同的 sql 字符串但我输入实际值而不是变量时,它可以工作。
如果有帮助,我还在前端运行 react/axios,在后端使用 mysql 运行 Node/Express
【问题讨论】:
-
我找到了this question,一个快速的解决方法是使用
??作为列名。在准备语句期间,您不应该动态插入列名,这就是您必须使用此解决方法的原因。它是关于防止 SQL 注入,其中用户发送更改任意列的操纵查询。更好的解决方案是根据attribute选择查询字符串,您可以通过在查询数组中查找提供的属性来自动执行此操作。 -
谢谢它解决了这个问题。好的,我会调查一下,这是我的第一个 SQL 项目 :)
标签: javascript mysql sql