Terence Eden. He has a beard and is smiling.
Theme Switcher:

Doctrine - how to use LIKE with dbal prepared statements

· 1 comment · 150 words · Viewed ~366 times


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!


Share this post on…

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.

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

To respond on your own website, write a post which contains a link to this post - then enter the URl of your page here. Learn more about WebMentions.