Reputation: 241
How to work with $_SERVER['QUERY_STRING'] and pagination?
When my table is sorted by this link:
<a href="'.$_SERVER['PHP_SELF'].'?sort_name=name&sort=asc" title="'.$lang['sorteer_asc'].'"></a>
My url becomes: relation.php?sort_name=adres&sort=asc
The I use an pagination link:
echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&page='.$i.'">'.$i.'</a> ';
And the url becomes: relation.php?sort_name=adres&sort=asc&page=2
So far so good but when browsing to other pages it can be as long as: relation.php?sort_name=adres&sort=asc&page=2&page=3&page=14&page=23&page=27
The age keeps appearing because of the $_SERVER['QUERY_STRING'], how can I clean up my url with only keeping the last page and ?sort_name=adres&sort=asc.
Or do you suggest an other solution of ordering and pagination?
Upvotes: 14
Views: 32870
Reputation: 145482
Instead of reusing QUERY_STRING
, you should assemble it anew with http_build_query()
.
// Merge $_GET with new parameter
$QS = http_build_query(array_merge($_GET, array("page"=>2)));
// You should apply htmlspecialchars() on the path prior outputting:
echo "<a href='" . htmlspecialchars("$_SERVER[PHP_SELF]?$QS") . "'> $i </a>";
Thus you have all current $_GET
parameters included, but can add or replace entries with new values. And it's ensured that each appears only once.
Upvotes: 33
Reputation: 6771
Don't use QueryString, just create a variable at the beginning of your script:
$pagerUrl = $_SERVER['PHP_SELF'].'?sort_name='.$_GET['sort_name']&sort=$_GET['sort'];
And use it in your link:
echo '<a href="'.$pagerUrl.'&page='.$i.'">'.$i.'</a> ';
Upvotes: 0
Reputation: 11779
Create a link builder ( simple php whitch make array( "a" => "b", "c" => "d" ) into ?a=b&c=d and rebuild it each time ( eg. put there "sort_name" => ... , "sort" => ..., "page" => ... )
If you still want to use QUERY_STRING - check if it contains &page=... and replace it ( both made by regexp )
Upvotes: 0