4

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){
});
Murad Elboudy
  • 463
  • 2
  • 11
  • 24

3 Answers3

3

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

Parabolord
  • 302
  • 3
  • 13
0

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;';
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

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});
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69