Paging in search failed when switching pages

Asked

Viewed 171 times

0

When incrementing a paging system in my search system, I get an error when passing from the first page to another..

Error:

http://localhost/admin/pages/search.php? search=Orixa? pag=2? pag=3

HTML form:

<form class="pesquisa" action="http://<?php echo $url; ?>/admin/paginas/pesquisa.php" method="GET">
    <input type="search" name="busca" class="input-busca" placeholder="Faça uma pesquisa.."  required>
</form>

SCRIPT PAGINATION:

<?php
    $url          = $_SERVER['SERVER_NAME'];  // imprime:www.site.com.br
    if(isset($_GET['pag'])){     
    $tamanhoGET = 0 - strlen($_GET['pag']);     
    $urlEndereco = substr($_SERVER ['REQUEST_URI'], 0, $tamanhoGET);    
    }else{
    $urlEndereco = $_SERVER ['REQUEST_URI'].'?pag=';
    } 
    ?>
    <div class="paginacao">
    <?php
    if($pag!=1){
        echo "<a href='http://".$url.$urlEndereco.($pag-1)."'> Anterior</a>"; 
    }
    if($contador<=$maximo){
        echo "<td>Existe apenas uma única página</td>";
    } else{
        for($i=1;$i<=$paginas;$i++){
            if($pag==$i){
                echo "<a class='link-ativo' href='http://".$url.$urlEndereco.$i."'> ".$i."</a>";
            }else{
                echo "<a href='http://".$url.$urlEndereco.$i."'> ".$i."</a>";
            }
        }
    }
    if($pag!=$paginas){
        echo "<a href='http://".$url.$urlEndereco.($pag+1)."'> Próxima</a>";
    }
    ?>
    </div>

SEARCH SCRIPT

<?php
include('../../config.php'); 
//if(empty($busca)) {
//    header('Location: ../');
//}    
    $busca = $_GET['busca'];

include('../header.php'); 

$sql_res=mysqli_query($conexao,"SELECT * FROM conteudo WHERE MATCH (titulo, texto, autor, id_categoria, id_pontos, id_orixas) AGAINST ('$busca') ORDER BY id DESC");
$contador=mysqli_num_rows($sql_res);
//Verificando se já selecionada alguma página
if(empty($_GET['pag'])){
    $pag=1;
}else{
    $pag = "$_GET[pag]";} //Pegando página selecionada na URL
if($pag >= '1'){
        $pag = $pag;
}else{
    $pag = '1';
}
$maximo=2; //Quantidade Máxima de posts por página
$inicio = ($pag * $maximo) - $maximo; //Variável para LIMIT da sql
$paginas=ceil($contador/$maximo);   //Quantidade de páginas 

$sql = "SELECT * FROM conteudo WHERE MATCH (titulo, texto, autor, id_categoria, id_pontos, id_orixas) AGAINST ('$busca') ORDER BY id DESC LIMIT $inicio, $maximo";
$exe = mysqli_query($conexao, $sql);
$contaRegistros = mysqli_num_rows($exe);
?>

When performing a search, the URL is as follows:

http://localhost/admin/paginas/pesquisa.php?busca=teste

And as we turn the page:

http://localhost/admin/paginas/pesquisa.php?busca=teste?pag=2?pag=3

However, the results are always the same.

Note: As I said, the paging system works perfectly in the other files, except in the search.. The link is getting as mentioned above on account of:

echo "<a href='http://".$url.$urlEndereco.$i."'> ".$i."</a>"; 

Where $url -> $_SERVER['SERVER_NAME']; and $urlEndereco -> $urlEndereco = $_SERVER ['REQUEST_URI'].'?pag=';

  • Thiago edited again: http://answall.com/a/111534/3635

2 answers

2

$_POST is for forms with <form method="POST">, to use page you will probably have to use GET, assuming the url looks like this:

 pagina.php?busca=1

In all variables GET or POST always check the values for example:

$busca = '';
if (false === empty($_GET['busca']) && is_numeric($_GET['busca'])) {
    $busca = $_GET['busca'];
}

The empty checks if the variable exists and if it is empty.

Looking at the code you sent me I noticed that you tried to recreate the url, but in these paging issues with querystring you can omit the url, this way for example:

<a href="?buscador=...&amp;pag=1">1</a>

The form should look like this:

<form class="pesquisa" action="pesquisa.php" method="GET">
    <input type="search" name="busca" class="input-busca" placeholder="Faça uma pesquisa.."  required>
</form>

Note: type=search maybe not supported by all browsers.

The pagination should look like this:

<div class="paginacao">
<?php
$busca = '';
if (false === empty($_GET['busca']) && is_numeric($_GET['busca'])) {
    $busca = htmlspecialchars($_GET['busca']);
}

$buscaQueryString = '?buscador=' . $busca . '&amp;pag=';//Gera a querystring da páginação

if($pag != 1){
    echo '<a href="', $buscaQueryString, $pag - 1,'">Anterior</a>'; 
}
if($contador<=$maximo){
    echo "<td>Existe apenas uma única página</td>";
} else{
    for($i=1;$i<=$paginas;$i++){
        if($pag==$i){
            echo '<a class="link-ativo" href="', $buscaQueryString, $i,'">', $i, '</a>';
        } else {
            echo '<a href="', $buscaQueryString, $i,'">', $i, '</a>';
        }
    }
}
if($pag != $paginas){
    echo '<a href="', $buscaQueryString, $pag + 1,'">Anterior</a>'; 
}
?>
</div>

And the other file like this:

<?php
include('../../config.php');

$busca = '';
if (false === empty($_GET['busca']) && is_numeric($_GET['busca'])) {
    $busca = htmlspecialchars($_GET['busca']);
}

include('../header.php');

$sql_res=mysqli_query($conexao,"SELECT * FROM conteudo WHERE MATCH (titulo, texto, autor, id_categoria, id_pontos, id_orixas) AGAINST ('$busca') ORDER BY id DESC");
$contador=mysqli_num_rows($sql_res);
//Verificando se já selecionada alguma página
if(empty($_GET['pag'])) {
    $pag=1;
}else{
    $pag = $_GET['pag'];
} //Pegando página selecionada na URL

if($pag >= 1){
        $pag = $pag;
}else{
    $pag = '1';
}
$maximo=2; //Quantidade Máxima de posts por página
$inicio = ($pag * $maximo) - $maximo; //Variável para LIMIT da sql
$paginas=ceil($contador/$maximo);   //Quantidade de páginas 

$sql = "SELECT * FROM conteudo WHERE MATCH (titulo, texto, autor, id_categoria, id_pontos, id_orixas) AGAINST ('$busca') ORDER BY id DESC LIMIT $inicio, $maximo";
$exe = mysqli_query($conexao, $sql);
$contaRegistros = mysqli_num_rows($exe);
?>

Note that the echo can work with comma instead of dots and I reversed the apostrophes with the quotation marks because for html it might be better to use quotation marks.

Read the documentation:

  • I made the appropriate changes, and when I go from page to URL is: http://localhost/admin/pages/search.php? search=test? pag=2 However, when passing again, the URL is: http://localhost/admin/pages/search.php? search=Orixa? pag=2? pag=3 That’s why the search system is creating the url as follows: echo "<a href='http://". $url. $urlEndereco. $i."'> ". $i."</a>"; $url is $_SERVER['SERVER_NAME']; and $urlEndereco is $urlEndereco = $_SERVER ['REQUEST_URI']. '? pag=';

  • Sorry for the comment, I will post the full code.

  • I posted the complete code. The pagination works perfectly. However, when I use it in the search, the links are like this that I quoted.

  • I guess I forgot to mention that the paging script is a separate file, which is only included in files that I use paging.. the search script is from the search.php file

  • The link was: http://localhost/admin/pages/search.php? search=&pag=2 I believe it is something along these lines: $buscaQueryString = '?busca=' . $search . '&amp;pag=';//Generate page querystring

Show 1 more comment

0

You’re putting the search field in a form? Try:

<form method="POST" action="buscar.php">
<input type="text" name="busca" placeholder="Digite aqui...">
<input type="submit" value="Buscar">
</form>

And in the search file, there should only be:

<?php
$busca = $_POST['busca']; 

seu código aqui

?>

If you show your code, it’ll be easier.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.