I'm looking for a more efficient, elegant and secure way to sort data displayed inside an HTML table. This is what I've come up with so far and it looks somewhat bloated / noobish.
I also thought of something like storing the sorting in a $_SESSION so I don't have to carry the currently selected order over to the next page "manually" within the URL. Maybe a "safe&simple" piece of JavaScript+PHP (but no frameworks please) would make sense? My thoughts go in circles for hours now.
<?php
$ro_arr = array(
"kid" => "kid",
"kwd" => "Keyword",
"cpc" => "ApproximateCPC",
"cmp" => "Competition",
"mov" => "MonthlyValue",
"gms" => "GlobalMonthlySearches",
"lms" => "LocalMonthlySearches",
"dfc" => "KeywordDifficulty",
"com" => "com",
"net" => "net",
"org" => "org",
);
if (!empty($_GET['ro']) && strlen($_GET['ro']) == 7 && array_key_exists($col = substr($_GET['ro'], 0, 3), $ro_arr)) {
$dir = (substr($_GET['ro'], 4, 3) == 'asc' ? "ASC" : "DESC");
$res_order = $res_arr[''. $col .''] ." ". $dir;
} else {
$_GET['ro'] = "kid_asc";
$res_order = "kid ASC";
}
?>
<!-- just for testing -->
<pre><?php echo $res_order; ?></pre>
<!-- done testing -->
<table>
<tr>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='kwd_asc')?"kwd_dsc":"kwd_asc"; ?>">Keyword</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='cmp_dsc')?"cmp_asc":"cmp_dsc"; ?>">Comp.</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='cpc_dsc')?"cpc_asc":"cpc_dsc"; ?>">Ad CPC</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='mov_dsc')?"mov_asc":"mov_dsc"; ?>">Value</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='gms_dsc')?"gms_asc":"gms_dsc"; ?>">Global Searches</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='lms_dsc')?"lms_asc":"lms_dsc"; ?>">Local Searches</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='dfc_asc')?"dfc_dsc":"dfc_asc"; ?>">Difficulty</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='com_dsc')?"com_asc":"com_dsc"; ?>">com</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='net_dsc')?"net_asc":"net_dsc"; ?>">net</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='org_dsc')?"org_asc":"org_dsc"; ?>">org</a></td>
</tr>
</table>