The problem is that when I load page 2 for example the URL becomes:
http://domain.com/index.php?restaurant-id=45¤tpage=2
And that\'s fine but when
You need to remove the previous value from the query string, e.g.:
preg_replace('/¤tpage=\\d+/', '', $_SERVER["QUERY_STRING"]);
instead of just $_SERVER["QUERY_STRING"].
I prefer to use a class like this to manipulate the query string:
final class QueryString
{
private $data;
private function __construct($start=null) {
if ($start === null)
$this->data = $_GET;
elseif (!is_array($start))
throw new InvalidArgumentException();
}
public function __isset($nm) {
return isset($this->data[$nm]);
}
public function __unset($nm) {
unset($this->data[$nm]);
}
public function __get($nm) {
return isset($this->data[$nm])?$this->data[$nm]:"";
}
public function __set($nm, $val) {
$this->data[$nm] = $val;
}
public function getString() {
return $this->getStringInternal(false);
}
public function getStringHTML() {
return $this->getStringInternal(true);
}
public function __toString() {
return $this->getString();
}
private function getStringInternal($HTML=false) {
if (empty($this->data))
return "";
$res = "?";
foreach ($this->data as $k => $v) {
if (!is_array($v)) {
if ($v === "")
$res .= urlencode($k).'&';
else
$res .= urlencode($k)."=".urlencode($v).'&';
}
else
foreach ($v as $vv) {
$res .= urlencode($k)."[]=".urlencode($vv).'&';
}
}
$res = substr($res,0,-1);
if ($HTML)
$res = htmlspecialchars($res);
return $res;
}
}
Then I can just do:
$qs = new QueryString();
$qs->currentpage = 7;
$url = "list.php" . $qs;
It will keep all the previous parameters, create "currentpage" if it doesn't exist and modify it if it exists.
Note: you can replace the loop of getStringInternal with http_build_query if you wish. I don't like the behavior of http_build_query when a key has several values; I prefer "a=1&a=2" to "a[0]=1&a[1]=2" and the original didn't add "[]" to the key; however PHP doesn't support multiple values without brackets in the key very well (I have to manualy parse the query string), Java web services I sometimes interface with do).