Does anyone know how to use SELECT WHERE IN
in node-mysql?
I've tried the code below, but I get the following error message:
'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'
This is my code:
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('/');
}
);
You have to use IN (?)
and NOT IN?
.
Any string manipulation may result in a SQL INJECTION backdoor.
You simply need to pass the tagArray
of values to node-mysql and it will handle the rest for you:
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('/');
}
);
For more information, see the section in the manual for how different values are automatically escaped: https://github.com/mysqljs/mysql#escaping-query-values
You need to quote your strings, not use backticks.
whereIn = '(';
for ( var i in tagArray ) {
if ( i != tagArray.length - 1 ) {
whereIn += "'" + tagArray[i] + "',";
}else{
whereIn += "'" + tagArray[i] + "'";
}
}
whereIn += ')';
For a more secure solution that avoids having to escape values, use? params like you would normally do, but create the param placeholders dynamically like this:
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) {
. . .
})
In case anyone is looking for answer to this in 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('/');
}
);
A working solution:
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('/');
}
);
No need to manually wrap tagArray in quotes. It is escaped by the mysql module.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.