Symfony - error because of addslashes in DQL query

1k views Asked by At

I do:

    $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();  

and when $text contains some ' than it throws error

[Syntax Error] line 0, col 150: Error: Expected end of string, got 'T' 500 Internal Server Error - QueryException

How to fix it?

1

There are 1 answers

5
kuboslav On
   $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();

Or try this:

   $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();