Search code examples
phpmysqlprepared-statement

How to SELECT LIKE with wildcard % with prepared statements


I have the following PHP code to run a MySQL query:

$stmt = $pdo->prepare('SELECT * FROM my_table WHERE first_row = :first_row AND second_row LIKE "%:second_row%"');
$stmt->execute(array(':first_row' => "foo", ':second_row' => "bar"));

PHP Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /home/kd37875/public_html/my_file.php:5

Why that?


Solution

  • Try this:

    $stmt = $pdo->prepare('SELECT * 
                           FROM my_table 
                           WHERE first_row = :first_row AND 
                                 second_row LIKE :second_row');
    $stmt->execute([':first_row'  => 'foo', 
                    ':second_row' => '%bar%']);
    

    So the % are simply part of the string, as they have always been.