2

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77
  • Add All your order by in an array then use $query = $query.implode(",", $orderBy); – Shantanu Mar 29 '17 at 07:38
  • 1
    Maybe it should be '==' in if condition instead of assigning '=' to $despos var – Vincent G Mar 29 '17 at 07:38
  • also think that if statement isn't right and it is even telling you the problem is '=' you can't have '=' with conditions '&&' and '||' to '!=' or '==' – Gert Mar 29 '17 at 07:53

2 Answers2

4
$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);
}
Shantanu
  • 692
  • 5
  • 20
1

Assuming that you know the order by params and their effective sorting order you could try something like this:

    $sortValues = [
    'bydate' => 'desc',
    'companyname' => 'asc'
];

$query = 'select * from market';

$count = count($sortValues);
$index = 0;
foreach($sortValues as $field => $sort){
    $index++;
    $query .= sprintf(' order by %s %s %s', $field, $sort, $index < $count ? ',' : '');
}
echo $query;

Result: select * from market order by bydate desc , order by companyname asc

Entrio
  • 31
  • 1
  • 8