PHP, SQL and sorting order

I searched for a good way to implement changing of sort order in php easily, but did not find a good way, so today i developed some handy code for sort order handling in PHP and want to share it. Maybe you find some downsides or maybe you like it.
You only have to configure the orderarray with your default sort order. The orderby parameter is filtered against that array, so there should be no danger of sql injection.

  "Modul" => "name ASC",
  "Date"=>"date ASC",
  "Text" =>"description ASC");
$orderby=implode(", ", $customorder);
foreach($customorder as $key=>$value){
  $orderstring=implode(",", array_unique(array_merge(array($key=>$value), $customorder)));
  $orderlinks.='<a href="index.php?orderby='.$orderstring.'">'
             . array_search($value,$orderarray) .'</a>';
print $orderlinks;
$query="SELECT name, date, desciption FROM some_table ORDER BY $orderby";
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: