How do I create a PDO parameterized query with a LIKE statement?

Viewed 111481

Here's my attempt at it:

$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');

$query->execute(array('value'));

while ($results = $query->fetch()) 
{
    echo $results['column'];
}
9 Answers

Figured it out right after I posted:

$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));

while ($results = $query->fetch())
{
    echo $results['column'];
}

I got this from php delusions

$search = "%$search%";
$stmt  = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();

And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query

I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:

<?php
     $player = $_POST['search'];  //variable from my search form
     $find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
     $find->execute(['%'.$player.'%']);

     while ($row = $find->fetch()) {
         echo $row['player']."</br>";
     }
?>

The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.

The only way I could get this to work was to put the %$search% into another variable.

    if(isset($_POST['submit-search'])){
         $search = $_POST['search'];
   }
    
        $query = 'SELECT * FROM posts WHERE post_title LIKE :search';
        $value ="%$search%";
        $stmt= $pdo->prepare($query);
        
        $stmt->execute(array(':search' => $value));

I don't know if this is the best way to do it, in the while loop I used:

while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){
Related