user852610
user852610

Reputation: 2265

create query with array parameter

I try to execute this query

$em->createQuery('select i from AcmePublicBundle:Public i where i.user in (:opc)');
$query->setParameter('opc', $opc);

where :opc is an array like this
$opc={array}[2]
  0 = {array}[1]
     id = "9"
  1 = {array}[1] 
     id = "10" 

I get this error

Notice: Undefined offset: 0 in...

If I try this

$em->createQuery('select i from AcmePublicBundle:Public i where i.usuario in (9, 10)');

everything is fine. But I have to pass $opc.

Any ideas?

Upvotes: 1

Views: 4564

Answers (2)

Juan Sosa
Juan Sosa

Reputation: 5280

Your $opc array should not be multidimensional. Try passing an array like this:

$opc=array(
  '9',
  '10'
);

instead of

$opc=array(
  array('id'=>'9'),
  array('id'=>'10')
);

Upvotes: 1

Jovan Perovic
Jovan Perovic

Reputation: 20201

Yeah, error seems quite appropriate because setParameter takes both array key and value into account and key represents field name. Therefore, you can't use matrix here.

$ids = array();
foreach ( $opc as $o ){
    $ids[] = (int)$o[1]; //be careful about data type (string, int etc)
}
$q = " .... WHERE id IN (:opc) ... ";
$q->setParameter('opc', $ids);

This should work....

Upvotes: 2

Related Questions