Remove character to search in database

Asked

Viewed 49 times

0

I’m having trouble creating a Function to make a search in the database and from the zip code complete the fields related to it, as address, neighborhood, city and state.

Obs: I have a mask in the field zip code

Function.php

<?php include("conn.php");

  /* Inicio da função para retornar campos a partir do CEP  GLOBAL */

       function cep($cep, $conn){
          $result = "SELECT * FROM cadcep WHERE cep = '$b_cep' LIMIT 1";
          $resultado = $conn->query($result);

          if($resultado){

              $row = mysqli_fetch_assoc($resultado);
              $valores['tipo_logr'] = $row['tipo_logr'];
              $valores['nome_logr'] = $row['nome_logr'];
              $valores['bairro'] = $row['bairro'];
              $valores['cidade'] = $row['cidade'];
              $valores['estado'] = $row['estado'];


          } else {
              return json_encode(array( 'error' => mysqli_error($conn) ));        
          }

              return json_encode($valores);

      }


      if(isset($_GET['cep'])){
              echo cep($_GET['cep'], $conn);
      }
   /* Fim da função para retornar campos a partir do CEP GLOBAL */

?>

JS to search from zip code

$(document).ready(function(){
          $("#cep").on("change", function(){

               var $tipo_logr = $("select[name='tipo_logr']");
               var $nome_logr = $("input[name='nome_logr']"); 
               var $bairro = $("input[name='bairro']"); 
               var $cidade = $("input[name='cidade']"); 
               var $estado = $("input[name='uf']");

               $.getJSON('function_cep.php',{ 
                       cep: $( this ).val() 
               },function( json ){
                       $tipo_logr.val ( json.tipo_logr );
                       $nome_logr.val ( json.nome_logr );
                       $bairro.val ( json.bairro );
                       $cidade.val ( json.cidade );
                       $estado.val ( json.estado );

               });
       });
});   
  • You’re missing in Function I’ll create the answer

  • I have a mask, I need to remove it and then carry out the search

  • you need to add the question

3 answers

1


Note that I have created comments to help you understand the answer. I created an array to avoid problems in the return, and at the beginning of Function used replace to remove character, you can use this for other situations, just use this way

function cep($cep, $conn){
   $chars = array(".","/","-","(", ")");
   $b_cep = str_replace($chars, "", $a_cep); 

Now complete code solving your problem

<?php include("conn.php");

/* Inicio da função para retornar campos a partir do CEP  GLOBAL */
    function cep($cep, $conn){
        /* Inicio removendo caracteres da mascara do campo cep para efetuar busca no banco de dados */
        $a_cep = str_replace(".", "", $cep);
        $b_cep = str_replace("-", "", $a_cep);
        /* Fim Removendo caracteres da mascara do campo cep para efetuar busca no banco de dados */
        $result = "SELECT * FROM cadcep WHERE cep = '$b_cep' LIMIT 1";

        $resultado = $conn->query($result);

        // DECLARA A VARIAVEL
        $valores = array();

        if($resultado){

            $row = mysqli_fetch_assoc($resultado);
            $valores['tipo_logr'] = $row['tipo_logr'];
            $valores['nome_logr'] = $row['nome_logr'];
            $valores['bairro'] = $row['bairro'];
            $valores['cidade'] = $row['cidade'];
            $valores['estado'] = $row['estado'];


        } else {
            return json_encode(array( 'error' => mysqli_error($conn) ));        
        }

            return json_encode($valores);

    }


    if(isset($_GET['cep'])){
            echo cep($_GET['cep'], $conn);
    }
/* Fim da função para retornar campos a partir do CEP GLOBAL */

?>
  • thank you worked perfectly

  • The answer is valid and works, but it would be better to remove anything other than digits of the variable would be more reliable to send to the database. But this way meets the need of @Victor T.

  • as I said at the beginning of the answer, just change str_replace, to delete the desired characters in this way => $chars = array(".","/","-","(", ")"); $tb_cep = str_replace($chars, """, $a_cep) I will edit the answer

  • Even so remains unviable from the moment you can work with Regex, much work stay feeding a variable with what you do not want. in that case he just wants much easier numbers a method that returns just that, imagine it is inputado 1 "A" in that variable it will pass, he will have to build just to add the "A" in the rejection variable?

0

Try it this way:

$.getJSON('function_cep.php?cep=' + $(this).val(), function(data) {
    console.log(data);
});

0

Create a method that returns to you only digits with Regex for better readability, I say to create a method because you may need elsewhere, add in a class Helper or any other that you store your help methods:

function apenasDigitos($value)
{
    return preg_replace('/[^0-9]/','',$value);
}

So before sending the CEP field to the database call this method. in its variable $b_cep, staying that way:

$b_cep = apenasDigitos($b_cep);

Your variable will now have nothing but numbers and so can move on and make the query in the database.

Browser other questions tagged

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