0

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. ?

5
  • What error do you get? What did you do to troubleshoot this? Commented Sep 19, 2013 at 1:21
  • "some syntax issue" - what is the issue? Any PHP or mysql errors? Commented Sep 19, 2013 at 1:21
  • You need a space between val and the sort order. Commented Sep 19, 2013 at 1:22
  • 1
    Are ASC and DESC defined constants? Commented Sep 19, 2013 at 1:22
  • 1
    If they are not constants, you should wrap them in quotes. $order = 'ASC'; Commented Sep 19, 2013 at 1:24

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Yes i resolved this now. I also need, once it is sorted in ASC, next time on click it is DESc. any points on that.. Thank you for your response

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.