We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

InWhere combined with andWhere

How do I combine InWhere with andWhere in a query?

    $rights = array('view_cat');
    $permissions = \user\UserPermission::query()
        ->inWhere('permission', $rights)
        ->andWhere('user_id = :user_id:')
        ->bind(array('user_id' => 1))
        ->execute();

Results in:

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



33.8k

You combine as you coded. The fact is that:

bind(array(1 => 1))

has to be

bind(array("user_id" => 1))

You didn't put the placeholder correctly in the binding array.

I posted the wrong code. I've updated my post, this still doesn't work.



33.8k

I'm seeing the docs and says that you can pass a second parameter to andWhere() that defines the binding array:

->andWhere('user_id = :user_id:', array('user_id' => 1))

If that doesn't work, try yo use a placeholder in inWhere() and set the binding parameters with the bind() method.

That worked. Thanks again RompePC :)



33.8k

I think that the problem was that you were passing a binding array, so Phalcon thought that all in your WHERE clauses was placeholded, throwing an error when discovering that ìnWhere() didn't have one.

That's what I thought, at least.



75

I know this thread is old but I was caught out by this too, so for anyone else who's stumbled across this...

Another solution is to rewrite your code as follows:

$permissions = \user\UserPermission::query()
    ->where('user_id = :user_id:')
    ->bind(array('user_id' => 1))
    ->inWhere('permission', $rights)
    ->execute();