Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keeping url parameters during pagination

Tags:

php

pagination

Is there any way to keep my GET parameters when paginating.

My problem is that I have a few different urls i.e

questions.php?sort=votes&author_id=1&page=3

index.php?sort=answers&style=question&page=4

How in my pagination class am I supposed to create a link to the page with a different page number on it but yet still keep the other parts of the url?

like image 724
yehuda Avatar asked Mar 12 '12 12:03

yehuda


2 Answers

If you wanted to write your own function that did something like http_build_query, or if you needed to customize it's operations for some reason or another:

<?php 
function add_edit_gets($parameter, $value) { 
    $params = array(); 
    $output = "?"; 
    $firstRun = true; 
    foreach($_GET as $key=>$val) { 
        if($key != $parameter) { 
            if(!$firstRun) { 
                $output .= "&"; 
            } else { 
                $firstRun = false; 
            } 
            $output .= $key."=".urlencode($val); 
         } 
    } 

    if(!$firstRun) 
        $output .= "&"; 
    $output .= $parameter."=".urlencode($value); 
    return htmlentities($output); 
} 

?>

Then you could just write out your links like:

<a href="<?php echo add_edit_gets("page", "2"); ?>">Click to go to page 2</a>
like image 57
Ryan Kempt Avatar answered Sep 28 '22 01:09

Ryan Kempt


You could use http_build_query() for this. It's much cleaner than deleting the old parameter by hand.

It should be possible to pass a merged array consisting of $_GET and your new values, and get a clean URL.

$new_data = array("currentpage" => "mypage.html");
$full_data = array_merge($_GET, $new_data);  // New data will overwrite old entry
$url = http_build_query($full_data);
like image 45
Naveen Kumar Avatar answered Sep 28 '22 00:09

Naveen Kumar