Doubt SQL query via primary key in PHP?

Asked

Viewed 60 times

0

I am starting in the PHP language, and need to return a simple query made in sql from a variable that receives the value typed by the user. Since, it will only display the primary key search result. However in the code below what you type in the field $buscar falls right into the else, as if all the value I put of primary key in the field $buscar were null. Can you help me?

Obs: The sql query is working, ex.: select * from empresa where cod = 123;

<?php
      $buscar = $_POST['buscar'];
      $sql = mysqli_query ($conexao, "SELECT * FROM loja where COD = '%$buscar%' ");


      $row = mysqli_num_rows($sql);

      if ($row != 0 && $row < 900) {

          while($linha = mysqli_fetch_array ($sql)) {
              $nome = $linha ['nome'];
              $contato = $linha['contato'];
              $endereco = $linha['endereco'];
              $coordenador = $linha['coordenador'];

              echo "<br /> <br  />";
              echo "<strong>  Contato:      </strong>".$nome;
              echo "<strong>  Contato:      </strong>".$contato;
              echo "<strong>  Coordenador:  </strong>".$coordenador;
              echo "<strong>  Endereço:     </strong>".$endereco;

          }

      } else {
        echo "Desculpe nenhum registro encontrado";

      }


?>
  • 1

    If the COD for a int you won’t be able to do the LIKE, I say this because the COD seems to be Codigo, which is usually number (and your example is also number). In fact, neither LIKE is being used, you are using only any string containing the %, which is not an integer number. You can’t understand what you want to do, because you mention that removing the % resolves.

  • I understood, I really did not pay attention in %, as I am not using a like would not need to put.. After removing the % search on Cod = code (rsrs) worked. Thank you very much !

  • The LIKE works in an integer column, the problem in doing the LIKE is to find any number that looks like what you are searching for, for example, in a number search 23 all the codes you have 23 at the beginning, middle or end would return in the result, see this SQL Fiddle. Your code only doesn’t work because you put = '%$buscar% whereas it should be LIKE '%$buscar%'.

  • @Laérciolopes, well pointed out, I believe that now he should do some CAST internally, in the newer versions, but I’m almost sure that was not possible before. Even so, it makes no sense to do this. But, the problem was even the presence of %.

1 answer

0

Try:

$sql = mysqli_query ($conexao, "SELECT * FROM loja where COD = {$buscar}");

Browser other questions tagged

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