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 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 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!


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

One thought on “Doctrine - how to use LIKE with dbal prepared statements”

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">