简体   繁体   中英

PHP select dropdown options putting specific options at top via mysql

My country table has these columns: rank_id, and country_name.

Right now it's ordering by name, but I'm trying to put a few specific countries at the top of the list in their rank order, and then the rest to follow via name.

Here's my query:

foreach ($db->query("SELECT * FROM " . config_item('cart', 'table_countries') . "") as $row)
$countries[] = $row;

Any ideas?

If you add a rank_order column with a default of 0 , and then change it to higher numbers for the few specific countries that you want at the top of the list.

You can then use this query to fetch your data:

SELECT * FROM table_countries ORDER BY rank_order DESC, country_name

Rows to be ordered by rank will always go first (in descending order), because their rank_order is higher than 0 . The rest will be ordered alphabetically by country_name .

A simple way of achieving this is to include a numerical display_order column in country_name that allows you to override the precedence set by ordering using name.

This would allow you to move countries arbitrarily to the top of the list based upon your needs and without having to alter queries at a later date.

You can then just do something like:

  SELECT *
  FROM country_name
  ORDER BY display_order ASC, name ASC;

You could tweak your "ORDER BY" clause by adding something like :

ORDER BY country_name='USA' DESC, country_name='Canada' DESC, country_name ASC

Since "country_name='USA'" returns "true" (or 1) only for USA and "false" (or 0) for all other countries and the order by is descending, USA would be first, then the same for Canada, then all others would come!

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