phpzend-framework

How do you query using an "IN" WHERE clause with Zend_Db_Adapter_Mysqli::fetchAll()?


I'm having a strange problem with Zend_Db_Adapter_Mysqli. I need to query multiple items by ID from my database, so I have the following SQL,

SELECT * FROM mytable WHERE id IN (1,2,3)

This query works fine.

I then try and do this programatically with Zend_Db_Adapter_Mysqli,

$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$ids = array(1,2,3);
$result = $adapter->fetchAll($sql, implode(',', $ids));

The problem is for the above PHP I only get back 1 result instead of the expected 3. I've tried just passing the $ids instead of using implode(), but I just get an error.

What am I doing wrong?


Solution

  • I'm not sure if it helps, but here's an answer on how to do it using Zend_Db_Select: How to create WHERE IN clause with Zend_Db_Select

    EDIT:

    Ok, if it really doesn't work, and you were planning on using a string anyway, can't you just do this:

    $ids = array(1,2,3);
    $sql = sprintf('SELECT * FROM mytable WHERE id IN (%s)', implode(',' $ids));
    $result = $adapter->fetchAll($sql);
    

    :)

    Or, even more wonderful:

    $ids = array(1,2,3);
    $sql = sprintf('SELECT * FROM mytable WHERE id IN (%s)', implode(',' array_fill('?', count($ids)));
    $result = $adapter->fetchAll($sql, $ids);
    

    However, I'm not sure fetchAll would accept this.