Problem with Bindvalue and PDO

Asked

Viewed 104 times

2

Hey, guys, good afternoon. I’m having trouble connecting by Bindvalue to my variable, note that I made the call, asked to return the values with Fetchall and it is returning an empty array. When I use normally without the bindValue it works. Could someone help me?

Code:

try {
    $conexao = new PDO("mysql:dbname=test;host=localhost" , "root", "");

    $nome = $_POST['nome'];

    $comando = $conexao ->prepare("select * from usuario where nome like '%:nome%'");

    $comando ->bindValue(':nome', $nome);
    $comando ->execute();

    $inf = $comando ->fetchAll();

    print_r($inf);

} catch (PDOException $ex){
    echo 'Erro: ' .$ex->getCode() . '<br>';
    echo 'Mensagem de erro: ' .$ex->getMessage();
}
  • Hello, enter the code in the question and not a print. I recommend to reading

  • Thanks for the tip

1 answer

1


To solve your problem you need to put the percentages in the variable and not in the instruction parameter SQL, example:

$comando = $conexao->prepare("SELECT * FROM usuario WHERE nome like :nome");
$comando->bindValue(':nome', "%{$nome}%");

and continue the rest as it is that automatically the parameter change is now in the correct format.

  • 1

    Thank you, friend it worked this way :)

Browser other questions tagged

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