0

I have a select menu on my website which displays all available countries. The countries come from my MySQL table which contains 10 countries, in a random order. I perfectly know how to retrieve all countries from my table and output them in my HTML select menu with PHP.

However, I was wondering what code-wise would be the most efficient way when I want to pick two specific countries to appear on top of my options list, with the other eight countries to be listed underneath? I would like to use as little sql and php as possible for achieving this goal.

Let's say I have the following table "countries":

   id   name
   1    United States
   2    France
   3    Brazil
   4    Puerto Rico
   5    India
   6    Australia
   7    Italy
   8    Denmark
   9    South Africa
   10   Oman

I would like to output the countries in a select menu and I want the list to start with Denmark and India (with their ids as option values).

My goal:

<select>
   <option value="8">Denmark</option>
   <option value="5">India</option>
   // ... the other eight countries underneath, in no specific order
</select>

The basic SQL query for retrieving all countries would be:

SELECT id, name FROM countries

How do I need to proceed for achieving my goal best?

2 Answers 2

1

If you want an alphabetical ORDER as followers, you can also use this statement

   SELECT id, name 
     FROM countries
     ORDER BY id=8 DESC, id=5 DESC, name ASC
Sign up to request clarification or add additional context in comments.

2 Comments

almost perfect. in the resulting array, 'Denmark' and 'India' are the last items. But I want them to be the first array items. How do I achieve that?
@Max i don't understand you ... this query returns an array Denemark, India, Australia, Brazil, ... and so on ...
1

You can use FIELD() function

SELECT id, name 
FROM countries
ORDER BY FIELD(name,'India','Denmark') DESC

or by using CASE

SELECT id, name 
FROM countries
ORDER BY CASE WHEN name = 'Denmark' THEN 0
              WHEN name = 'India' THEN 1
              ELSE 2 END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.