Solved $query Order BY ...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
alweb
Forum Newbie
Posts: 3
Joined: Wed Sep 22, 2010 8:41 pm

Solved $query Order BY ...

Post by alweb »

I have a query which I need to order by state but I just can't figure it out a simple thing.

Using a simple command works fine

Code: Select all

$query = 'SELECT b.*'.	          
' FROM #__my_cat a'.
' INNER JOIN #__items b'.
' on  a.id_items = b.id '.
' where a.id_cat = '.$id.
' order by state = "WISCONSIN" DESC';

but when changed to

Code: Select all

$mystate = 'WISCONSIN';

$query = 'SELECT b.*'.	          
' FROM #__my_cat a'.
' INNER JOIN #__items b'.
' on  a.id_items = b.id '.
' where a.id_cat = '.$id.
' order by state = $mystate DESC';


It doesn't work. What m'I missing?

Thank you
Last edited by alweb on Sun Mar 20, 2011 2:04 pm, edited 1 time in total.
gully_mi_seh
Forum Newbie
Posts: 14
Joined: Fri Mar 18, 2011 8:48 pm

Re: $query Order BY ...

Post by gully_mi_seh »

in the last code-line you have used a simple quote , php will not read the content of your variable $mystate .you can correct this by using this instead :
'order by state = '.$mystate.' DESC'; or you can use a double quote : "order by state = $mystate DESC"; .or "order by state =,$mystate,DESC"
When placing a variable within a string you have to make sure to your variable accessible to php.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: $query Order BY ...

Post by social_experiment »

If your $mystate value is from user input you should escape it properly to avoid injection.

Code: Select all

order by state = '" . mysql_real_escape_string($mystate) . "' DESC
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
alweb
Forum Newbie
Posts: 3
Joined: Wed Sep 22, 2010 8:41 pm

Re: Solved $query Order BY ...

Post by alweb »

Thank you gully_mi_seh and social_experiment.
Post Reply