How to do a LIKE database query in Symfony2
Asked Answered
B

5

17

This should be simple but I can't find a working example. Here's a controller method that throws the error "Invalid parameter number: number of bound variables does not match number of tokens". I'm posting the "searchterm" variable successfully but can't get the query to work. What is missing? Thanks!

 public function searchAction()
{
    $request = $this->getRequest();

    $searchterm = $request->get('searchterm');

    $em = $this->getDoctrine()->getEntityManager();

    $query = $em->createQuery("SELECT n FROM AcmeNodeBundle:Node n WHERE n.title LIKE '% :searchterm %'")
             ->setParameter('searchterm', $searchterm);

    $entities = $query->getResult();

    return array('entities' => $entities);

}
Biota answered 11/9, 2011 at 16:41 Comment(0)
M
37

Working example from my Symfony2 project:

$qb = $this->createQueryBuilder('u');
$qb->where(
         $qb->expr()->like('u.username', ':user')
     )
     ->setParameter('user','%Andre%')
     ->getQuery()
     ->getResult();
Mowry answered 15/6, 2013 at 17:59 Comment(0)
A
11

You should dump the created query for easier debugging.

I can only suggest you also try the querybuilder:

$qb = $em->createQueryBuilder();
$result = $qb->select('n')->from('Acme\NodeBundle\Entity\Node', 'n')
  ->where( $qb->expr()->like('n.title', $qb->expr()->literal('%' . $searchterm . '%')) )
  ->getQuery()
  ->getResult();

doc

Alive answered 12/9, 2011 at 6:8 Comment(0)
C
9

I think this option also helps:

$qb = $this->createQueryBuilder('u');
$qb->where('u.username like :user')
     ->setParameter('user','%hereIsYourName%')
     ->getQuery()
     ->getResult();
Coaler answered 9/8, 2017 at 11:41 Comment(0)
B
2

WHERE n.title LIKE '% :searchterm %'

should be

WHERE n.title LIKE :searchterm

public function searchAction() {
    $request = $this->getRequest();

    $searchterm = $request->get('searchterm');

    $em = $this->getDoctrine()->getEntityManager();

    $query = $em->createQuery("SELECT n FROM AcmeNodeBundle:Node n WHERE n.title LIKE :searchterm")->setParameter('searchterm', $searchterm);

    $entities = $query->getResult();

    return array('entities' => $entities);

}
Biauriculate answered 30/4, 2014 at 14:44 Comment(0)
T
0

maybe AcmeNodeBundle\Node? In DQL AcmeNodeBundle:Node :Node - named parameter

Teamster answered 12/9, 2011 at 5:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.