【问题标题】:Symfony - error because of addslashes in DQL querySymfony - 由于 DQL 查询中的 addlashes 导致的错误
【发布时间】:2012-02-12 17:39:37
【问题描述】:

我愿意:

    $text = '%'.addslashes($text).'%';


    $images = $this->getDoctrine()->getEntityManager()
        ->createQuery("SELECT img, cat, u
                       FROM AcmeMainBundle:Image img
                       JOIN img.category cat
                       JOIN img.user u
                       WHERE img.title LIKE '$text' OR img.description LIKE '$text'
                       ORDER BY img.id DESC")
        ->getResult();  

当 $text 包含一些 ' 时,它会抛出错误

[语法错误] line 0, col 150: Error: Expected end of string, got 'T' 500 内部服务器错误 - QueryException

如何解决?

【问题讨论】:

    标签: symfony doctrine-orm dql addslashes


    【解决方案1】:
       $images = $this->getDoctrine()->getEntityManager()
            ->createQuery("SELECT img, cat, u
                           FROM AcmeMainBundle:Image img
                           JOIN img.category cat
                           JOIN img.user u
                           WHERE img.title LIKE :text OR img.description LIKE :text
                           ORDER BY img.id DESC")
            ->setParameter('text', $text)
            ->getResult();
    

    或者试试这个:

       $text = "%".$text."%";
       $images = $this->getDoctrine()->getEntityManager()
            ->createQueryBuilder()
            ->select(array('img','cat','u'))
            ->from('AcmeMainBundle:Image', 'img')
            ->innerJoin('img.category', 'cat')
            ->innerJoin('img.user', 'u')
            ->where('img.title LIKE :title OR img.description LIKE :description')
            ->orderBy('img.id','DESC')
            ->setParameter('title', $title)
            ->setParameter('description', $title)
            ->getResult();
    

    【讨论】:

    • 它有什么变化?我以前试过,但我不记得我是用':text'还是只用:text。顺便提一句。现在我在查询之前创建了整个 WHERE 部分,我只做“... WHERE $search”,我也尝试过“... WHERE :search”,但它没有任何改变。
    • 哦……我忘记了百分比。你必须像在 PDO 中一样使用它——$text = "%".$text."%";
    • 您的意思是删除“addslashes(...)”吗?见上面我的代码。
    • 是的,你不需要它。 Doctrine 用于逃避 PDO。
    • 还是不行。阅读我在此答案下的第一条评论。
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多