Reputation: 12373
I've got a search function which is triggered by a GET request which looks something like: http://localhost:8888/TESTCI/search/get_books?i-slider=7.0&rt-slider=70&start-year=1955&end-year=2013&genre=all&language=all
That's all fine and the search function works as expected. The problem arises when I want to sort the results based on year, genre, language etc. I have a number of links on the results page which I am trying to use to sort. Given that I have no form on the page to resubmit the values my idea was to make the links equal to the current URL plus the GET parameter for sorting. An example of the year sort being:
$year_sort_class = "ui-btn-active ui-state-persist sort-desc";
$year_sort_order = "&sort-by=year-asc";
<li class="<?php echo $year_sort_class ?>"><a href="<?php echo $_SERVER['REQUEST_URI'].$year_sort_order ?>">Year</a></li>
The obvious problem that arises after I sort is that now $_SERVER['REQUEST_URI']
is equal to my original URL plus the &sort-by=year-asc
. Meaning that any further sorts, whether by genre, language or year again, will be appended continuously to the URL resulting in URL that might looks something like
http://localhost:8888/TESTCI/search/get_books?i-slider=7.0&rt-slider=70&start-year=1955&end-year=2013&genre=all&language=all&sort-by=rt-desc&sort-by=i-desc&sort-by=year-desc&sort-by=i-desc
after 4 sorts.
What is the solution to this problem? Am I missing something fundamental here and completely complicating the issue?
Upvotes: 1
Views: 1625
Reputation: 2793
You could introduce a baseUrl variable and wrap it in a function
function buildLink($sort = "year-asc", $foo = "default") {
$baseUrl = "http://localhost:8888/TESTCI/search/get_books?";
return $baseurl.$sort."&".$foo;
}
print "<a href='".buildLink("year-desc")."'>My Book</a>
Upvotes: 0
Reputation: 1173
Try something like this...
<?
$href = explode('?',$_SERVER['REQUEST_URI']);
$href = $href[0];
$qs = array();
foreach ($_GET as $param => $val) {
if ($param != 'sort-by') $qs[$params] = $val;
}
?>
<a href="<?=$href.'?'.implode('&',$qs).'&sort-by="year"?>">Year</a>
Upvotes: 1
Reputation:
Do a regular expression match to remove the previous sort leftover.
preg_replace('/\&sort\-by\=([a-zA-Z0-9-_]+)/','',$_SERVER['REQUEST_URI']);
Upvotes: 0