Prepared SELECT LIKE - where to put %

I’m trying to fathom out where to put the %s in order to do a LIKE comparison. Can anyone help please?

$query  = 'SELECT * FROM table WHERE keywords LIKE :keywords;';
$stmt   = $db->prepare($query);
$stmt->bindParam(':keywords', $keywords);
$stmt->execute();
$result = $stmt->fetchAll();

Thanks

SELECT * FROM table WHERE keywords LIKE %:keywords% ;

Or, at least I think it should be. I’ve never tried it with parameterized queries in PHP.

Is keywords allowing more than one word?

HTH,

:slight_smile:

Thanks @WolfShade. I tried that first but it gives a syntax error. I also tried

$stmt->bindParam(':keywords', '%'.$keywords.'%');

without luck. I think $keywords is going to be just one word otherwise I’ll need to do an equality check in a loop.

:slight_smile: That is what I was going to suggest, next. Heh…

:slight_smile:

1 Like

Oh bum! (Am I allowed to say that?)

Right sort of thought, either the wrong function or wrong place.

So there are two ways to do it:

1: bindValue instead of bindParam

$stmt->bindValue(':keywords', '%'.$keywords.'%');

2: Correct $keywords.

$stmt->bindParam(':keywords', $keywords);
//...Other bits of code...
$keywords = "%".$keywords."%";
$stmt->execute();

bindParam works by REFERENCE - which means it doesnt matter what $keywords contains when you bind it, when you go to execute, PDO will check the value of $keywords at that time to determine what to put into your query. (Which is why bindParam works with loops - you can bindParam outside the loop, and just change the value of the variable inside the loop without needing to re-bind.

 $stmt = $pdo->prepare("INSERT INTO mytable(keys) VALUES (:keywords)")
 $stmt->bindParam(':keywords', $keywords);
 foreach($myarray AS $keywords) {
    $stmt->execute(); //Note that $keywords changes with each iteration of the loop because of FOREACH.
 }
1 Like

Brill, thanks squire! :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.