Reputation: 21
I am trying to concatenate a variable to my sql query in php to have my table sorted according to that variable. For eg:
if ($_GET['sort'] == 'Val'){
$query .= " ORDER BY val";
}
I need a variabvle $sortorder to be concatenated with this query. so that i get sorted query in ASC or DESC. What i do is
$order = ASC ;
if ($_GET['sort'] == 'Val'){
$query .= " ORDER BY val" ."$order";
}
and write the logic for
if($order==ASC){$order= DESC}
and vice versa. but it doesnt work. table is not displayed. some syntax issue?
Anyone could help on this. ?
Upvotes: 0
Views: 56
Reputation: 476557
You need to introduce a space. Otherwise SQL will read ORDER BY valDESC
So:
$query .= " ORDER BY val " ."$order";
Or more compact:
$query .= " ORDER BY val $order";
You can check that your query is as expected by simply printing it
echo $query ;
This simple debugging can help you to resolve problem
Upvotes: 2
Reputation: 780724
Use:
$query .= " ORDER BY val $order";
You need a space between the column name and the sort order. Your code was generating:
ORDER BY valASC
If you simply did echo $query;
before trying to execute it, you would surely have seen this. Please do some basic, obvious debugging before posting here.
Upvotes: 0