[英]SELECT WHERE IN in node-mysql
有谁知道如何在 node-mysql 中使用SELECT WHERE IN
?
我试过下面的代码,但收到以下错误消息:
'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 ''(`PHP`,`apache`)'' at line 1'
这是我的代码:
whereIn = '(';
for ( var i in tagArray ) {
if ( i != tagArray.length - 1 ) {
whereIn += "`" + tagArray[i] + "`,";
}else{
whereIn += "`" + tagArray[i] + "`";
}
}
whereIn += ')';
console.log(whereIn);
client.query(
'SELECT tag_id FROM tag WHERE tag_name IN ?',
[whereIn],
function(err, result, fields) {
client.destroy();
if (err) {
throw err;
}
console.log(result);
res.redirect('/');
}
);
您必须使用IN (?)
而不是IN?
.
任何字符串操作都可能导致 SQL INJECTION 后门。
您只需将值的tagArray
传递给 node-mysql,它将为您处理其余的:
client.query(
'SELECT tag_id FROM tag WHERE tag_name IN (?)',
[tagArray],
function(err, result, fields) {
client.destroy();
if (err) {
throw err;
}
console.log(result);
res.redirect('/');
}
);
有关更多信息,请参阅手册中有关如何自动转义不同值的部分: https ://github.com/mysqljs/mysql#escaping-query-values
您需要引用您的字符串,而不是使用反引号。
whereIn = '(';
for ( var i in tagArray ) {
if ( i != tagArray.length - 1 ) {
whereIn += "'" + tagArray[i] + "',";
}else{
whereIn += "'" + tagArray[i] + "'";
}
}
whereIn += ')';
对于避免必须转义值的更安全的解决方案,请使用? params 就像你通常做的那样,但是像这样动态地创建 param 占位符:
var inlist = '';
for(var i=0; i<ids.length; i++) {
inlist += '?,';
}
inlist = inlist.substring(0,inlist.length-1);
var sql = 'SELECT a, b, c FROM mytable WHERE id in (' + inlist + ')';
conn.query( sql, ids, function(err, rows) {
. . .
})
万一有人在 2021 年寻找这个问题的答案。
client.query(
'SELECT tag_id FROM tag WHERE tag_name IN (?)',
[['val1', 'val2']],
function(err, result, fields) {
client.destroy();
if (err) {
throw err;
}
console.log(result);
res.redirect('/');
}
);
一个可行的解决方案:
client.query(
'SELECT tag_id FROM tag WHERE tag_name IN ?',
[tagArray],
function(err, result, fields) {
client.destroy();
if (err) {
throw err;
}
console.log(result);
res.redirect('/');
}
);
无需手动将 tagArray 括在引号中。 它由 mysql 模块转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.