简体   繁体   中英

How can I pass the correct variables in a URL in PHP for my paging?

I am working on paging in PHP

  • I need it to work on any folder so root/ root/folder1/ root/folder1/folder2/ would all work
  • It should pass the page number variable for the script to work in the URL but also retain any other variables in the URL that may be present with any amount of variables passed in tthe URL

Here is what I have so far for the link based on being @

http://domain.com/test/paging/index.php?var=cool&var2=coo2l&page=1


$selfurl = "http://".$_SERVER['SERVER_NAME'].dirname($_SERVER['PHP_SELF'])."";

This would create this: http://domain.com/test/paging/


$qry_str = $_SERVER['argv'][0];

This would create this: var=cool&var2=coo2l&page=1


So far so good, it works no matter how deep the directory system is and passes ANY and ALL variables that may exist in the pages URL (NOTE; I know it assumes it is always the index file I will fix that later)

So all of these links below would get passed through my paging links;

http://domain.com/test/paging/?page=1
http://domain.com/test/paging/?var=coo2l&page=1 http://domain.com/test/paging/?var=cool&var2=coo2l&page=1

Here is the problem, below is an
example of my NEXT and PREVIOUS link, it works
but the problem is after I go to the
first page, it will keep adding

&page=THE-NUMBER-HERE so when you get to page 3 it

would be like

&page=THE-NUMBER-HERE&page=THE-NUMBER-HERE&page=THE-NUMBER-HERE

instead of

&page=THE-NUMBER-HERE

The links;

 <a href="<?PHP echo $selfurl;?>/?<?PHP echo $qry_str;?>&page=<?PHP echo $start-$pagesize;?>" class="bluelinkbold">Next</a> <a href="<?PHP echo $selfurl;?>/?<?PHP echo $qry_str;?>&page=<?PHP echo $start-$pagesize;?>" class="bluelinkbold" >Previous</a> 



How can I resolve this path correctly?


it's simple:

  1. don't use $_SERVER['argv'][0], construct URL by yourself on every request.
  2. use preg_replace to remove existing page variable from $_SERVER['argv'][0] then add new one:

    $url_without_page_var=preg_replace('/page=(\\d+)/i','',$_SERVER['argv'][0]);

I had a similar problem when passing a page number after an id variable.
mysite.php?id=16&page=1&page=2&page=1 and so on... Inspired by Sergei, I remove the existing variables using PHP_SELF, then reload my id and get the new page at the same time.

href="' . $_SERVER['PHP_SELF'] .'?id='. $row['id'] . '&page=' . $pages->next . '">Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM