Saving URL parameters during pagination

Is there a way to save the GET options when paginating.

My problem is that I have several 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 should I create a link to a page with a different page number, but still save the other parts of the URL?

+4
source share
4 answers

In short, you simply parse the URL and then add the parameter at the end or replace it if it already exists.

 $parts = parse_url($url) + array('query' => array()); parse_str($parts['query'], $query); $query['page'] = $page; $parts['query'] = http_build_str($query); $newUrl = http_build_url($parts); 

This code sample requires the PHP HTTP module for http_build_url and http_build_str . Later, you can replace http_build_query , and for the first, implement the PHP user space if you do not have the module installed.

Another alternative is to use the Net_URL2 package, which offers an interface for various URL operations:

 $op = new Net_URL2($url); $op->setQueryVariable('page', $page); $newUrl = (string) $op; 

It is more flexible and expressive.

+5
source

You can use http_build_query () for this . It is much cleaner than manually deleting an old parameter.

It should be possible to pass a combined array 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); 
+6
source

If you want to write your own function that did something like http_build_query, or if you needed to configure it for one 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 can simply write your links, for example:

 <a href="<?php echo add_edit_gets("page", "2"); ?>">Click to go to page 2</a> 
+2
source

How about saving your page parameter in the session, so you don’t have to change the URL of each page?

0
source

Source: https://habr.com/ru/post/917287/


All Articles