Field search loses value by clicking on another page

Asked

Viewed 89 times

0

I have a table referring to accesses of a certain system. In it I have a pagination with all the accesses of the system, when I search a certain access in the search field, the pagination applies to the fields but when clicking on the link, it comes back as if it were from the beginning. From what I realized, the field and variable loses its value by clicking on the page, as I could save the value I placed in the field within the search field or in a variable?

I am passing the page link by the url. I put the value of the variable cammpo search in the left corner for example

inserir a descrição da imagem aqui

manual_sistema.php

            <div class="col s12 l12 paginacao" >
            <div class="col l5 s12 right">
                <form method="post">
                    <div class="input-field col s12 l12">
                        <input id="pesquisa" name="pesquisa" type="text">
                        <label for="pesquisa">Pesquisar Acesso...</label>
                    </div>
                </form>
            </div>



        </div>

        <div class="col l12 s11" id="acessosTable"><!-- DIV TABLE !-->

            <?php
                include_once 'pesquisaAcesso.php';
            ?>

        </div>

<script>
    $("#pesquisa").keyup(function(){
    var busca = $("#pesquisa").val();

    $.post('pesquisaAcesso.php', {busca: busca},function(data){
      $("#acessosTable").html(data);
    });


  });

</script>

searchAccess.php

include_once '../conecta_banco.php';


@define('QTDE_REGISTROS', 8); //define os acessos listados por pagina  
@define('RANGE_PAGINAS', 4); //define as paginas que ira mostrar de acordo com a atual.


$pagina_atual = (isset($_GET['page']) && is_numeric($_GET['page'])) ?  $_GET['page'] : 1; //operador ternario || verifica se existe o numero da pag, caso nao, atribui a pagina 1 ao mesmo
$linha_inicial = ($pagina_atual -1) * QTDE_REGISTROS;  //calcula a linha inicial da consulta para mostrar a lista dos acessos

@$busca = $_POST['busca'];

$query = $conecta->prepare("SELECT * FROM acessos WHERE descricao LIKE '%$busca%'  LIMIT {$linha_inicial}, " . QTDE_REGISTROS);
$query->execute();
$fetchAll = $query->fetchAll();
$count= $query->rowCount();

//conta todos os registros que existem na tabela  
$sqlContador = "SELECT COUNT(*) AS total_registros FROM acessos where descricao LIKE '%$busca%' ";  
$stm = $conecta->prepare($sqlContador);  
$stm->execute();  
$valor = $stm->fetch(PDO::FETCH_OBJ);  

/* Idêntifica a primeira página */  
$primeira_pagina = 1;  

/* Cálcula qual será a última página */  
$ultima_pagina  = ceil($valor->total_registros / QTDE_REGISTROS);  

/* Cálcula qual será a página anterior em relação a página atual em exibição */  
$pagina_anterior = ($pagina_atual > 1) ? $pagina_atual -1 :  1;  

/* Cálcula qual será a pŕoxima página em relação a página atual em exibição */  
$proxima_pagina = ($pagina_atual < $ultima_pagina) ? $pagina_atual +1 :  1;  

/* Cálcula qual será a página inicial do nosso range */    
$range_inicial  = (($pagina_atual - RANGE_PAGINAS) >= 1) ? $pagina_atual - RANGE_PAGINAS : 1 ;  

/* Cálcula qual será a página final do nosso range */    
$range_final   = (($pagina_atual + RANGE_PAGINAS) <= $ultima_pagina ) ? $pagina_atual + RANGE_PAGINAS : $ultima_pagina ;  

/* Verifica se vai exibir o botão "Primeiro" e "Pŕoximo" */  
$exibir_botao_inicio = ($range_inicial < $pagina_atual) ? 'mostrar' : 'esconder';

/* Verifica se vai exibir o botão "Anterior" e "Último" */  
$exibir_botao_final = ($range_final > $pagina_atual) ? 'mostrar' : 'esconder';

if($count >0){

    echo $busca;
    echo '<ul class="pagination center" >';
    echo '<li class="waves-effect"><a href="manual_sistema.php?page='.$pagina_anterior.'"><i class="material-icons">chevron_left</i></a></li>';
    echo '';

    for ($i=$range_inicial; $i <= $range_final; $i++){
        $marcador = ($i == $pagina_atual) ? 'active' : '' ;
        echo '<li class="waves-effect '.$marcador.' paginas"><a href="manual_sistema.php?page='.$i.'">'.$i.'</a></li>';  
    }

    echo '';
    echo '<li class="waves-effect"><a href="manual_sistema.php?page='.$proxima_pagina.'"><i class="material-icons">chevron_right</i></a></li>';
    echo '</ul>';



    echo '<table class="highlight bordered">';
    echo '<head>';
    echo '<tr>';
    echo '<th>Acesso</th>';
    echo '<th>Permissão</th>';
    echo '<th>Descrição</th>';
    echo '<th>Sistema</th>';
    echo '</tr>';
    echo '</head>';

    foreach($fetchAll as $acessoPesquisa){

        echo '<tr>';
        echo '<td style="user-select: none;"><b>'.$acessoPesquisa['nome_acesso'].'</b></td>';
        echo '<td>'.$acessoPesquisa['permissao'].'</td>';
        echo '<td style="user-select: none;">'.$acessoPesquisa['descricao'].'</td>';
        echo '<td style="user-select: none;">'.$acessoPesquisa['sistema'].'</td>';
        echo '</tr>';
    }

}else{
    echo '<br><div class="center">Nenhum acesso encontrado com os parâmetros pesquisados.</div>';
}
echo '</table>';

Pastebin.com/p7wh9bPn

  • Enter the code at all times here, you can even leave somewhere else and pass the link, but it has to be in the question at all times all relevant code

  • Preferably never put external links, this prevents one day this link from working and the question becomes incomprehensible. @Guilhermecostamilam

  • I fixed the code

  • @Francisco, there is no problem leaving external links (on the contrary, it helps a lot when there is a code running somewhere where one can try some solution in a simple way, since here it is not possible to run languages like Python, Java, SQL, etc)as long as you always have the code here too

  • I hadn’t answered your question ?

2 answers

3


Every time you change pages the post data is reset so you lose the $_POST['search'], so you should save it somewhere, the easiest place is to save it in Sesssion, just putting it should already work.

// pesquisaAcesso.php
// ...
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (isset($_POST['busca'])) { 
    $_SESSION['busca'] = $_POST['busca'];
}

@$busca = $_SESSION['busca'];
// ...

Documentation of Session.
A question like yours here.

  • It worked out man! I just have to adapt now to my code. Thank you very much!

  • Could I save field value when switching pages based on my code ?

1

Sessions solve the problem but are not necessary

In jQuery trade for

$.get('pesquisaAcesso.php?busca='+busca, function(data){ ... })

It’s more semantic to make a GET request

In PHP, take the search variable for GET instead of POST and add this variable to the navigation links

@$busca = $_POST['busca'];

//...

echo $busca;
echo '<ul class="pagination center" >';
echo '<li class="waves-effect"><a href="manual_sistema.php?page='.$pagina_anterior.'&busca='. $busca.'"><i class="material-icons">chevron_left</i></a></li>';
echo '';

for ($i=$range_inicial; $i <= $range_final; $i++){
    $marcador = ($i == $pagina_atual) ? 'active' : '' ;
    echo '<li class="waves-effect '.$marcador.' paginas"><a href="manual_sistema.php?page='.$i.'&busca='. $busca.'">'.$i.'</a></li>';  
}

echo '';
echo '<li class="waves-effect"><a href="manual_sistema.php?page='.$proxima_pagina.'&busca='. $busca.'"><i class="material-icons">chevron_right</i></a></li>';
echo '</ul>';

Browser other questions tagged

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