Florian Mithieux
Florian Mithieux

Reputation: 503

Doctrine setParameter and Invalid parameter number

After many tries, I think I finally know the documentation by heart. Then, I need your help .. I don't understand why Doctrine show me this error :

Invalid parameter number: number of bound variables does not match number of tokens

Here is my code :

$qb = $this->em->createQueryBuilder();
$qb->select('m')
   ->from('Entities\Marque', 'm')
   ->leftJoin('m.magasin', 'ma')
   ->where('m.nom = :marque AND ma.nom LIKE :magasin')
   ->setParameter('marque', $marque)
   ->setParameter('magasin', '%'.$matchesNumber[1].'%');
$results = $qb->getQuery()->getArrayResult();

Thank you in advance for your answer.

Upvotes: 7

Views: 22505

Answers (4)

Yes Barry
Yes Barry

Reputation: 9846

This also happens if you accidentally use more than one where(), which happened to me once.

$em    = $this->getEntityManager();
$query = $em->createQueryBuilder()
    ->from('AppBundle:SomeEntity', 's')
    ->select('s')
    ->where('s.foo = :foo')
    ->where('s.bar = :bar') // <- HERE
    ->setParameter('foo', 'Foo Value')
    ->setParameter('bar', 'Bar Value');

Should be:

$em    = $this->getEntityManager();
$query = $em->createQueryBuilder()
    ->from('AppBundle:SomeEntity', 's')
    ->select('s')
    ->where('s.foo = :foo')
    ->andWhere('s.bar = :bar') // <- CHANGE TO andWhere()
    ->setParameter('foo', 'Foo Value')
    ->setParameter('bar', 'Bar Value');

Hope this helps someone.

Upvotes: 12

macchokri
macchokri

Reputation: 41

$qb = $this->em->createQueryBuilder();
$parameters = array('marque'=>$marque, 'magasin'=>'%'.$matchesNumber[1].'%');
$qb->select('m')
   ->from('Entities\Marque', 'm')
   ->leftJoin('m.magasin', 'ma')
   ->where('m.nom = :marque')
   ->andWhere('ma.nom LIKE :magasin')
   ->setParameters($parameters);

$results = $qb->getQuery()->getArrayResult();

Upvotes: 4

Florian Mithieux
Florian Mithieux

Reputation: 503

I'm so sorry .. I just found my error .. Later, like more later in my code .. I type a new query with my old "$qb" .. I'm such a noob !

Upvotes: 7

DerStoffel
DerStoffel

Reputation: 2633

I presume ->setParameter overrides the previous one.

For multiple Parameters use:

->setParameters(['key1' => $value1, 'key2' => $value2])

See Doctrine Upgrade:

From now on, parameters in queries is an ArrayCollection instead of a simple array. This >affects heavily the usage of setParameters(), because it will not append anymore parameters >to query, but will actually override the already defined ones. Whenever you are retrieving a >parameter (ie. $query->getParameter(1))

Doctrine Upgrade Description

Maybe that also applies to setParameter?

Upvotes: 8

Related Questions