Doctrine - how to use LIKE with dbal prepared statements
I'm just getting started with Symfony, so I'm blogging some of the weird things I'm finding.
I want to use Doctrine dbal to search a database for a partial match. For example searching for "smith" should find "blacksmith" and "smithy".
I have a prepared statement like this:
PHP
$queryBuilder = $conn->createQueryBuilder();
$queryBuilder
->select("whatever")
->from("table")
->where("name LIKE '%?%'")
->setParameter(0, $query);
But I get the error:
The number of variables must match the number of parameters in the prepared statement.
The solution is annoyingly simple. The escaping has to be in the parameter itself. Like this:
PHP
...
->where("name LIKE ?")
->setParameter(0, "%{$query}%");
I hope that's helpful to someone - even if that someone is me in a few years' time!
More comments on Mastodon.