Error with GET in PHP pagination

0

I'm trying to adapt the relative links to absolutes in my paging script. However, whenever I try to go back or forward a page, the link looks like this:
http://localhost/textos?pag=2?pag=3

Script:

<?php
$url          = $_SERVER['SERVER_NAME'];
$urlEndereco  = $_SERVER ['REQUEST_URI'];
?>
<table border="1">
   <tr>
<?php
if($pag!=1){
   echo "<td><a href='http://".$url.$urlEndereco."?pag=".($pag-1)."'> Página Anterior</a></td>"; 
}
if($contador<=$maximo){
   echo "<td>Existe apenas uma única página</td>";
}
else{
   for($i=1;$i<=$paginas;$i++){
if($pag==$i){
   echo "<td  style='background: red'><a href='http://".$url.$urlEndereco."?pag=".$i."'> ".$i."</a></td>";
}else{
   echo "<td><a href='http://".$url.$urlEndereco."?pag=".$i."'> ".$i."</a></td>";
}
}
}
if($pag!=$paginas){
   echo "<td><a href='http://".$url.$urlEndereco."?pag=".($pag+1)."'> Próxima Página</a></td>";
}
?>
</tr>
</table>

However, if I use the code below, it works normally. But I happen to use pagination with an include on several pages to leave the code clean, having an easier control.

echo "<td><a href='textos?pag=".($pag+1)."'> Próxima Página</a></td>";

I also noticed that $ urlEndereco is causing this, since it does $_SERVER['REQUEST_URI']; , always returning the end of url: http://localhost/textos?pag=2?pag=3

    
asked by anonymous 21.01.2016 / 15:18

2 answers

1

There are several methods to solve.

Cause:

  

$urlEndereco is inserting ?pag=2 , when you try to add the%   new ?pag= it is doubling.

Resolve:

  

Remove 2 from ?pag=2 and just insert the new number instead.

Use the following to remove the last number:

    <?php
    if(isset($_GET['pag'])){ 
   // Se existir pag ele corta!

      $tamanhoGET = 0 - strlen($_GET['pag']); 
    // Terá o tamanho do GET, ou seja, 1 caractere ou 2...
    // O número zero é para torna-lo negativo!

      $urlEndereco = substr($_SERVER ['REQUEST_URI'], 0, $tamanhoGET);
    // Logo o http://localhost/textos?pag=2 irá se tornar http://localhost/textos?pag=
    // Se tiver na página 12 irá cortar os 2 ultimos números.

    }else{
      $urlEndereco = $_SERVER ['REQUEST_URI'].'?pag=';
   // Este é o caminho padrão

    }  


    ?>

Now just change your echo to just enter the number, instead of the whole parameter.

Use something similar:

<?php
     echo "<td><a href='http://".$url.$urlEndereco.($pag+1)."'> Próxima Página</a></td>";
    // O $urlEndereço não terá o número, agora irá possuir o $pag+1. 
?>

Overview:

I believe it is self explanatory, but in general it will remove the parameter number and insert a new number, rather than adding a new parameter as it was doing, which would eventually double it.

    
21.01.2016 / 15:32
1

Try this way because PHP_SELF is relative to the root of the document. Delete $ urlEndereco

$url = $_SERVER['PHP_SELF'];

    
21.01.2016 / 15:36