0

This is an example of a query I've tried:

const order = req.params.order
connection.query('select * from students order by first_name key=?', order, (err)=>{
...
});

By default without specifying the way, I retrieve the information ordered by first_name asc.

I would like the data ordered by asc or desc according what has been sent through the params.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rob
  • 1
  • 1
  • Does this answer your question? [Make MySQL's ORDER BY dynamic in node.js](https://stackoverflow.com/questions/39625688/make-mysqls-order-by-dynamic-in-node-js) – toing_toing Apr 06 '20 at 17:57

2 Answers2

0

Im assuming that req.params. order = ASC or DESC. So try this:

connection.query(`select * from students order by fisrt_name ${order}`, order, (err)=>{
...
});

or

const myQuery = `select * from students order by fisrt_name ${order}`;
connection.query(myQuery, order, (err)=>{
...
});
Oriol
  • 1
0

Do this. If order is undefined it will order by ASC by default. If it is defined, it will order by the parameter. I hope this is what you were looking for.

connection.query(
    `select * from students order by first_name ${order ? order : 'ASC'}`
    , order, (err)=>{
...
});
awrfisher
  • 196
  • 5