Search code examples
phppaginationget

Save all $_GET values except one to the next page


I have a table which is filled with some rows and it is showed based on a pagination script I have. In this table there are two GET forms which handle the sorting and the rows per page. When the forms are sent the URL becomes for example: ?page=2&order=desc&view=10.

The problem is that I don't know how to pass those order and view values when i click on a different page. This is the link to the previous (or next) page on my script:

$pagination.= "<li><a href=\"$targetpage?page=$prev\">Prev</a></li>";

$prev is $page - 1 where $page is $_GET['page']. When I am on page 2 and I need to get to page 1, i just click the above link and I need to take with me order and view on the URL.

I tried with

$build_query = http_build_query($_GET);

editing the above line with this:

$pagination.= "<li><a href=\"$targetpage?page=$prev{$build_query}\">Prev</a></li>";

But of course as soon as i click the link it gives me

?page=1page=2&order=desc&view=10

So page is repeated. I also tried to unset($_GET['page']); but I don't know how to pass the previous page value to set then $_GET['page'] correctly.

EDIT 1:

The entire pagination code is written inside a function so $_GET values to pass is different between pages.


Solution

  • You could build you own query string function:

    function generate_query_string($page_num)
    {
        $query = '?';
        foreach ($_GET as $key => $value) {
            if ($key == 'page') {
                $query.=$key.$page_num;
            } else {
                $query.=$key.'='.$value.'&';
            }
        }
        // remove trailing '&'
        return substr($query, 0, strlen($query) - 1);
    }
    

    You can pass the desired page number in as an argument when you call the function.