php

Adding comma after MySQL query based on condition (desc or asc)


I am dynamically creating a query for search, based on search I need to append query with des|asc.

For example if the user click bydate I will append order by bydate desc, again if the user wants to search company name I append order by companyname asc. This is done on condition.

For example if the query is

select * from market

and if the user searches by date query becomes

 select * from market order by bydate desc

and if the user searcher by companyname query becomes

Now if the previous query contains asc or desc I need to insert comma, so the query becomes

select * from market order by bydate desc, companyname

If I don't check and insert comma query becomes

select * from market order by bydate desc companyname -- without comma

So inserting comma based on condition

 $query = 'select * from market order by bydate desc';

    if(  ($despos = false) && (  ( strripos($query, 'desc') !=== false && ($despos =  strripos($query, 'desc')) ) ||  ( strripos($query, 'asc') !=== false && ($despos =  strripos($query, 'asc'))  )   ) && $despost !===false   && $despos >(strlen($query)-7)  ) $query.=", ";

But the query shows the following error:

( ! ) Parse error: syntax error, unexpected '=' in E:\wamp\www\sugumar\php\1.php on line 5


Solution

  • $query = "select * from market";
    $orderBy = array();
    

    if the user searches by date

    array_push($orderBy, "bydate desc");
    

    if the user searcher by companyname query

    array_push($orderBy, "companyname asc");
    
    if(count($orderBy) > 0) {
       $query = $query." order by ".implode(",", $orderBy);
    }