问题
I want to make the ORDER BY
dynamic in mysql query in node.js. But it's not working. I console.log
the multiQuery variable and everything looks perfect but when ran it simply doesn't work. This is what I have:
var order,
multiQuery;
if(req.query.o){
order = req.query.o;
}else{
order = "views";
}
multiQuery = 'SELECT COUNT(Category) AS Count FROM posts;';
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views FROM posts WHERE Category = ' + connection.escape(category) + ' ORDER BY' + connection.escape(order) + 'DESC LIMIT ' + start_from + ', 15;';
connection.query(multiQuery, function(err, result){
});
回答1:
This does not work:
SELECT foo FROM bar ORDER BY 'baz';
This does work :
SELECT foo FROM bar ORDER BY baz;
Did you try removing the quotes that connection.escape
adds?
Try using this:
function escapeSansQuotes(connection, criterion) {
return connection.escape(criterion).match(/^'(\w+)'$/)[1];
}
then use escapeSansQuotes(connection, order)
instead of connection.escape(order)
.
回答2:
try using a proper spacing for each token
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views
FROM posts WHERE Category = ' + connection.escape(category) +
' ORDER BY ' + connection.escape(order) +
' DESC LIMIT ' + start_from + ', 15;';
回答3:
Check if you did enabled the multi-query into your connection object.
http://nickolayconsulting.com/node-js-and-multiple-sql-calls-in-one-query/
Support for multiple statements are disabled by default for security reasons (it allows for SQL injection attacks if values are not properly escaped). To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
来源:https://stackoverflow.com/questions/39625688/make-mysqls-order-by-dynamic-in-node-js