SELECT ... WHERE name LIKE bind_param

Asked

Viewed 518 times

2

I have the following code:

<?php 
$link = new mysqli("localhost", "root", "minhasenha", "meu_db");

$produto = $_GET['q'];

$produto = '%'.$produto.'%';

$busca_produtos = $link->prepare("SELECT id, nome_com from clientes where nome_com LIKE ?");

$busca_produtos->bind_param("i", $produto);

$busca_produtos->bind_result($id, $nome_com);

$busca_produtos->store_result();

if($busca_produtos->num_rows() == 0){

    echo "Nenhum produto encontrado";

} else{

    while ($busca_produtos->fetch()) {
        echo $nome_com;
    }
}
?>

However, I can’t accomplish the bind_param() together with the LIKE of SELECT. Note that I have declared the variable $produto above and concatenei with the characters %, but still returns the following message

No product found

I wanted to know how to format the code correctly?

  • And why are you doing the bind_param with the parameter i, that represents an integer value? It should not be s?

  • I changed to string, but still no data display!

1 answer

3


The LIKE in numbers (integers, double etc.) i for s. Also missed calling the method execute() after the bind_param() because it sends the query to the database without it is not possible to recover the result.

Your code should be:

$busca_produtos = $link->prepare("SELECT id, nome_com from clientes where nome_com LIKE ?");
$busca_produtos->bind_param("s", $produto);
if(!$busca_produtos->execute()){
   echo $busca_produtos->error;
}

$busca_produtos->bind_result($id, $nome_com);

if($busca_produtos->num_rows() == 0){
    echo "Nenhum produto encontrado";
} else{
    while ($busca_produtos->fetch()) {
        echo $nome_com;
    }
}

Related:

Select with Prepared statements Mysqli

Mysqli bind with an array of values

  • Man. Thank you very much. We really missed $busca_produtos->execute(); - It was a distraction. In the rush we forget. As they say: the programmer needs time, rs. Big hug

  • The variable is with no quotes? $produto = ' "%'.$produto.'%" '; and missing $busca_produtos->execute(); like is string: s

  • @Ivanferrer did a test here put the right joker without quotation marks.

Browser other questions tagged

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