如何在 PDO 准备语句中使用 LIKE 子句?

2021-12-26 00:00:00 php mysql pdo

我有一个这样的 sql 查询:

I have a sql query like this:

SELECT * FROM tbl_name WHERE title Like "%:needle%"

当我使用此语句手动查询 MySQL 数据库时,它可以工作.但是,当我将它与 PDO 一起使用并使用与我手动查询相同的 :needle 值时,它只返回一个空结果集.

When I query the MySQL db manually with this statement it works. But when I use it with PDO and with the same values for :needle as I queried manually It just returns an empty result set.

utf8 编码会影响它的行为吗?

Does utf8 encoding affects the behavior of it?

推荐答案

使用 PDO,可以这样做:

With PDO, this can be done like:

$stmt = $db->prepare("SELECT * FROM tbl_name WHERE title LIKE :needle");
$needle = '%somestring%';
$stmt->bindValue(':needle', $needle, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

相关文章