PHP/Mysql search with Javascript returning data to HTML

Asked

Viewed 3,098 times

3

I’m setting up a search page where on the HTML page a search button when clicked calls a Javascript function that passes the typed content to a php page. This PHP page must connect to the database, search for what was typed and return some values in a table, this table must be returned to the html page (through javascript), and shown in a div with id="Resultado" but he’s making a mistake:

Warning: mysqli_query(): (HY000/2008): Mysql client Ran out of memory in /home/irbpe586/public_html/irbapp/testesearch/search.php on line 7 An error occurred in the query!

Please if anyone can help me I’m so grateful.

Javascript within the html:

<script type="text/javascript">
$("#pesquisa_1").click(function() {
    if($(this).val() != ""){
        var rua = $('#pesquisa_rapida').val();
        var urlmanual = "pesquisa.php";
        $.post(urlmanual, {"pesquisa_rapida" : pesquisa_rapida} ,function(result) {
            var div = document.getElementById("#Resultado"); 
            div.innerHTML = result;
            alert (result);
        });
}});
</script>

HTML:

<input type="text" id="pesquisa_rapida" name="pesquisa_rapida" class="form-control item-formulario" placeholder="Pesquisa rápida..."/>

<button type="submit" id="pesquisa_1" name="opcao" value="1" class="btn botao1 item-formulario"><span class="glyphicon glyphicon-search"></span></button>

PHP:

<?php

if(isset($_POST['pesquisa_rapida'])){
    $input = $_POST['pesquisa_rapida'];
    @$con = mysqli_connect("host.com.br", "user", "******", "database");
    if($con){
       $query = mysqli_query($con, "SELECT * FROM `resultado` WHERE nm_candidato LIKE '%$pesquisa_rapida%'");
        if($query){
            if(mysqli_num_rows($query) > 0){

                //tabela
                echo "<table border=1 cellspacing=0 align=center>";
                echo "<tr bgcolor=#c0c0c0 style=color:white>";
                echo "  <td> UF do Estado </td>";
                echo"   <td> Nome do Municipio </td>";
                echo"   <td> Ano das Eleicoes </td>";
                echo"   <td> Nome do Candidato </td>";
                echo"   <td> Nome do Candidato na Urna </td>";
                echo "</tr>";

                while($result = mysqli_fetch_assoc($query)){

                    echo "<tr>";
                    echo "<td>"; echo 'UF do Estado: '.$result['sg_uf'].'<br />'; echo "</td>";
                    echo "<td>"; echo 'Nome do Municipio: '.$result['nm_municipio'].'<br />'; echo "</td>";
                    echo "<td>"; echo 'Ano das Eleicoes: '.$result['dt_ano'].'<br />'; echo "</td>";
                    echo "<td>"; echo 'Nome do Candidato: '.$result['nm_candidato'].'<br />'; echo "</td>";
                    echo "<td>"; echo 'Nome do Candidato na Urna: '.$result['nm_candidatourna'].'<br />'; echo "</td>";
                    echo "</tr>";
                }
            }else{
                echo 'Sem dados para essa busca!';
            }
        }else{
            echo 'Ocorreu um erro na query!';
        }
    }else{  
        echo 'Ocorreu um erro na ligação à base de dados!';
    }

}else{
    echo 'Introduzir valor!';
}
?>
  • Try paging the results, only for testing in select put one limit 100

  • Thus? $query = mysqli_query($con, "SELECT * FROM resultado_votacao_candidato_zona_eleicaomunicipal WHERE nm_candidato LIKE '%$pesquisa_rapida%' LIMIT 100");

  • That, the mistake is gone now?

  • yes, it worked out..

  • tin is q is not showing only q typed

  • it’s all coming out of the bank

  • and does not appear in html, the table is in php

  • It should not be : "SELECT * FROM resultado WHERE nm_candidate LIKE '%$input%'" since you passed the value of $_POST["quick search"] to the $input variable? I believe you’re doing a quote like "'"

  • @That’s right, but I’ve got it, thank you.

Show 5 more comments

1 answer

1

I transformed the logic to Ajax, this way, it will be better in performance and visualization, I have not tested, but by the structure, I believe it will work:

Edit your javascript like this:

<script type="text/javascript">
    function pesquisaRapida(pesquisa_rapida, resultView) {
         var url_pesquisa = "pesquisa.php";
         $.ajax({
             type: 'POST',
             url: url_pesquisa + '?rand=' + new Date().getTime(),
             async: true,
             cache: false,
             data :{'pesquisa_rapida': pesquisa_rapida},
             dataType : "json",
             complete: function(d) {
             },
             success: function(jsonData) {
                    $('#'+resultView).html(construirTabela(jsonData));   
             }
     });

    }

    function construirTabela(data) {
    var contentHTML = '';
    if (data.status == 1) {
      contentHTML +='<p>'+data.message+'</p>\
                     <table border=1 cellspacing=0 align=center>\
                     <tr bgcolor=#c0c0c0 style=color:white>';
      for (var kTitle in contentHTML.titulos_tabela) {
           contentHTML += '<td>' + contentHTML.titulos_tabela[kTitle] + "</td>\n";
      }
      contentHTML += '</tr>';
      for (var kData in contentHTML.dados_tabela) {
          contentHTML +=  '<tr>\
                             <td>'+contentHTML.dados_tabela[kData][0]+'</td>\
                             <td>'+contentHTML.dados_tabela[kData][1]+'</td>\
                             <td>'+contentHTML.dados_tabela[kData][2]+'</td>\ 
                             <td>'+contentHTML.dados_tabela[kData][3]+'</td>\ 
                             <td>'+contentHTML.dados_tabela[kData][4]+'</td>\
                           <tr>';                
      }

    } else {
      contentHTML = '<p>'+data.message+'</p>'; 
    } 
     return contentHTML;
   }

    $(function(){

     $('#pesquisa_1').on('click', function(){
      var elPesq = $('#pesquisa_rapida');
      var pesquisa = elPesq.val();

          if (pesquisa == "") {
              alert('Preencha o termo antes de fazer a busca!');
              elPesq.focus();
              return false;
          } else {
             pesquisaRapida(pesquisa, 'resultado');
          }
     });

    });
</script>

And your HTML like this:

<input type="text" id="pesquisa_rapida" name="pesquisa_rapida" class="form-control item-formulario" placeholder="Pesquisa rápida..."/>
<div id="resultado"></div>
<button type="submit" id="pesquisa_1" name="opcao" class="btn botao1 item-formulario"><span class="glyphicon glyphicon-search"></span></button>

And your PHP like this:

<?php

$con = new mysqli("host.com.br", "user", "******", "database");
if (!$con) {
    printf("Erro na conexão. Erro: %s\n", mysqli_connect_error());
    exit();
}


if (isset($_POST['pesquisa_rapida'])) {
    $input = $_POST['pesquisa_rapida'];
    $param = "%{$input}%";
    $stmt = $con->prepare("SELECT * FROM `resultado` WHERE nm_candidato LIKE ? ");
    $stmt->bind_param("s", $param);
    $stmt->execute();
    $result = $stmt->get_result();
    $collection = new array();
    $titles_tabela = array(
                      'UF do Estado',
                      'Nome do Município',
                      'Ano das Eleições',
                      'Nome do Candidato',
                      'Nome do Candidato na Urna'
                    );
    if ($result && $result->num_rows) {

       $message = "Encontramos ({$result->num_rows}) dados para sua pesquisa.";
       $status = '1';

        while ($row = $result->fetch_array(MYSQLI_NUM)) {

               $collection[] = array(
                                "UF do Estado: {$row['sg_uf']}",
                                "Nome do Município:  {$row['nm_municipio']}",
                                "Ano das Eleições: {$row['dt_ano']}",
                                "Nome do Candidato: {$row['nm_candidato']}",
                                "Nome do Candidato na Urna: {$row['nm_candidatourna']}"
                               );

        }

     } else {
        $status = '0';
        $message = "Não encotramos dados para '{$input}'.";
     }
} else {
     $status = '2';
     $message = "Digite o termo para a pesquisa!";

}

  $json_view = array(
         'titulos_tabela' => $titles_tabela,
         'dados_tabela'=> $collection,
         'status' => $status,
         'message' => $message,
  );

echo json_encode($json_view);
?>

Browser other questions tagged

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