如何使用准备好的语句 SELECT LIKE 通配符 %

How to SELECT LIKE with wildcard % with prepared statements

我有以下 PHP 代码 运行 MySQL 查询:

$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

为什么?

试试这个:

$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%']);

所以 % 只是字符串的一部分,一如既往。