1
votes

I'm using PDO bindValue to search terms through my database. Is my syntax all wrong? I'm not getting the result I'm supposed to

$term = $_GET['s'];
$s_pdo = $dbh->prepare("SELECT * FROM table WHERE value = ':search'");
$s_pdo -> bindValue(':search',"%".$term."%",PDO::PARAM_STR);
$s_pdo -> execute();

while($s_row = $s_pdo->fetchAll(PDO::FETCH_ASSOC)){
    echo $s_row['value'];
}

Does anyone see anything wrong here? I do have the value in my mysql. I'm matching exactly in mysql to test if my search function works.

Thanks!

2
Try running the query from phpmyadmin and see if it returns any rowsshxfee

2 Answers

2
votes

try to remove the % from the bindValue part..:

$s_pdo = $dbh->prepare("SELECT * FROM table WHERE value = :search");
$s_pdo -> bindValue(':search',$term,PDO::PARAM_STR);

or use LIKE so you can leave the %:

$s_pdo = $dbh->prepare("SELECT * FROM table WHERE value LIKE :search");
$s_pdo -> bindValue(':search',"%".$term."%",PDO::PARAM_STR);
1
votes

You don't need to quote prepared placeholders. Also, when using %term%, you should be using LIKE instead of = The prepare action does it for you!

$term = $_GET['s'];
$s_pdo = $dbh->prepare("SELECT * FROM table WHERE value LIKE :search");
$s_pdo -> bindValue(':search',"%".$term."%",PDO::PARAM_STR);
$s_pdo -> execute();

while($s_row = $s_pdo->fetchAll(PDO::FETCH_ASSOC)){
    echo $s_row['value'];
}

Also, next time, for better error debugging, enable PDO::ERRMODE_EXCEPTION using PDO::setAttribute() method.