Home » Php » php – Doctrine setParameter and Invalid parameter number

php – Doctrine setParameter and Invalid parameter number

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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?

Answer:

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 !

Answer:

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