简体   繁体   中英

How to do massive sort by different fields with SQL query on php?

I show to admin all users with different fields. Admin want to has a sort of every user's field.
How I can do it with one SQL query on php?
I know how to do it with many SQL queries. But it's will be like 1 query = 1 function. I don't know another method to do it.
Maybe, I can do button for every field and to do check, if button click on, it return name of field by post query. Than I put $_POST['field'] to SQL query like this:

$db = Db::getConnection(); // Connect to database
$field = $_POST['field'];

$result = $db->query("
SELECT id
     , name
     , tel
     , role
     , friend
     , date_reg
     , date_log
     , referral
     , balance
     , all_cash
     , timer
     , ip
     , status 
  FROM users 
 WHERE role = 'user' 
 ORDER 
    BY" . $field . " DESC
");

This is bad idea or have you different better method?

Apart from the SQL injection you need to fix, you should rather do the sort in PHP. Sorting with MySQL only works well if the field you are sorting on is indexed. In this case, I doubt (and it would not be good) that ALL the fields are indexed.

So remove the ORDER BY , make the query (that can be cached !!) and use usort for instance to sort your array !

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM