0

having a bit of trouble. Basically I have created some pagination. The problem is each time I click on a page number url it just adds the parameter to the url even if it already exists.

so for instance I land on the page. My url is now example.com/page?pagenum=1, I click the second page so my url is now example.com/page?pagenum=1&pagenum=2. Now it all works fine but as you can imagine is going to get a bit messy so would rather it update the parameter that's already in the URL. I'm currently using the following to get the current page URL:

<?php
    function curPageURL() {
     $pageURL = 'http';
     if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
     $pageURL .=      $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
     $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>

and then the Link is something like:

<a href='<?php echo curPageURL(); ?>&pagenum=<?php echo "1"; ?>'> 1 </a>

Update I have other paremeters in the URL I need to keep, I only need to update 'pagenum'

David
  • 181
  • 1
  • 2
  • 12

2 Answers2

0

You can use http_build_query like so:

$all_params = $_GET;
$all_params["page"] = "2";
$link = "page.php?" . http_build_query($all_params); // "page.php?page=2&foo=bar"
Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

The problem exists because REQUEST_URI contains both the path and query string, and you're appending a new query string to that every page turn. To extract the path, you could use this code, taken from this answer:

$path = strtok($_SERVER["REQUEST_URI"], '?');

You can then copy existing query string fields, but remove pagenum:

$fields = $_GET;
unset($fields['pagenum']); // remove any existing pagenum value
$path .= '?' . http_build_query($fields); // re-append the query string

You could then use more or less your existing link code:

<a href='<?php echo $path; ?>&pagenum=<?php echo "1"; ?>'> 1 </a>
Community
  • 1
  • 1
George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • Hey, thanks that does seem to almost do what i want, the problem is I have a bunch of other parameters in the url I need to keep, this replaces them all. Is there anything I can do about that? – David Sep 17 '13 at 08:14