Page 1 of 1

Solved $query Order BY ...

Posted: Fri Mar 18, 2011 8:05 pm
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

Re: $query Order BY ...

Posted: Fri Mar 18, 2011 9:20 pm
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.

Re: $query Order BY ...

Posted: Sun Mar 20, 2011 11:30 am
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

Re: Solved $query Order BY ...

Posted: Sun Mar 20, 2011 2:06 pm
by alweb
Thank you gully_mi_seh and social_experiment.