Bryan Bojorque
Bryan Bojorque

Reputation: 168

Sort MySQL data using a variable

I've come in peace lol.

I have a question how do I achieve this kind of algorithm(i'll just use an example im bad at english)

in index.php page. i have sent a get method (term=dog&name=john)

and in process.php how do I sort my data using this get method data where in the page will display all the "term=dog" and the first that will display is the "name=john" followed by whatever (name="whatever").

the page display example would be

dog
**john**

dog
peter

dog
jane

my fail attempt only shows all the list of dogs but i cannot specify what goes first in this case is "john"

heres my failed result

dog
peter

dog
jame

dog
**john**

it sorts on according to its ID property in the table different from what i want it to be.

SELECT * FROM animal WHERE race = '$term' ORDER BY '$name'

This is all the code i have so far i haven't started to sort it because i don't know

Upvotes: 0

Views: 258

Answers (3)

Jared Kipe
Jared Kipe

Reputation: 1187

SELECT race, name, IF(name = 'john', 1, 0) AS o FROM animal WHERE race = 'dog' ORDER BY o DESC;

Should do it for you, if I understand correctly. You want all rows WHERE race = 'dog' but with a specified name at the top.

Upvotes: 0

Zane Bien
Zane Bien

Reputation: 23125

So it seems to me you want to get all rows where race = '$term' and if name = '$name', then put that row at the top of the result set. You can use this solution:

SELECT   * 
FROM     animal 
WHERE    race = '$term'
ORDER BY CASE name WHEN '$name' THEN 0 ELSE 1 END, name

Upvotes: 3

Justin Swanhart
Justin Swanhart

Reputation: 1856

SELECT * FROM animal WHERE race = '$term' ORDER BY (name = '$name') DESC

Upvotes: 0

Related Questions