在node-mysql中selectWHERE

有谁知道如何在节点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 ?

任何string操作都可能导致SQL INJECTION后门程序。

你需要引用你的string,而不是使用反引号。

 whereIn = '('; for ( var i in tagArray ) { if ( i != tagArray.length - 1 ) { whereIn += "'" + tagArray[i] + "',"; }else{ whereIn += "'" + tagArray[i] + "'"; } } whereIn += ')'; 

对于一个更安全的解决scheme,避免不必要的值,使用? 像你一样的参数通常会做,但像这样dynamic地创buildparam占位符:

 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) { . . . }) 

工作解决scheme:

 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模块转义。