doctrine2 dql, use setParameter with % wildcard when doing a like comparison

前端 未结 2 1306
刺人心
刺人心 2020-12-24 06:18

I want to use the parameter place holder - e.g. ?1 - with the % wild cards. that is, something like: \"u.name LIKE %?1%\" (though this throws an error). The docs have the fo

相关标签:
2条回答
  • 2020-12-24 07:00

    When binding parameters to queries, DQL pretty much works exactly like PDO (which is what Doctrine2 uses under the hood).

    So when using the LIKE statement, PDO treats both the keyword and the % wildcards as a single token. You cannot add the wildcards next to the placeholder. You must append them to the string when you bind the params.

    $qb->expr()->like('u.nickname', '?2')
    $qb->getQuery()->setParameter(2, '%' . $value . '%');
    

    See this comment in the PHP manual. Hope that helps.

    0 讨论(0)
  • 2020-12-24 07:05

    The selected answer is wrong. It works, but it is not secure.

    You should escape the term that you insert between the percentage signs:

    ->setParameter(2, '%'.addcslashes($value, '%_').'%')
    

    The percentage sign '%' and the symbol underscore '_' are interpreted as wildcards by LIKE. If they're not escaped properly, an attacker might construct arbirtarily complex queries that can cause a denial of service attack. Also, it might be possible for the attacker to get search results he is not supposed to get. A more detailed description of attack scenarios can be found here: https://stackoverflow.com/a/7893670/623685

    0 讨论(0)
提交回复
热议问题