How to do MySQL IN clauses using Zend DB?

2019-04-06 17:38发布

问题:

I'm trying to fetch rows that are in an array of integers that I have using Zend Framework 1.11.

$this->dbSelect
         ->from($table_prefix . 'product_link')
         ->joinLeft($table_prefix . 'product_link_name', $table_prefix . 'product_link.product_link_name_ref_id = ' . $table_prefix . 'product_link_name.product_link_name_id')
         ->where('product_ref_id IN (?)', implode(', ', $product_ids));

When I use the __toString() method of $this->dbSelect, I get

SELECT `phc_distrib_product_link`.*,
     `phc_distrib_product_link_name`.* 
FROM `phc_distrib_product_link` 
LEFT JOIN `phc_distrib_product_link_name` 
ON phc_distrib_product_link.product_link_name_ref_id = phc_distrib_product_link_name.product_link_name_id 
WHERE (product_ref_id IN ('10, 12'))

This only returns rows satisfying the condition where product_ref_id = 10. How can I get the IN clause to be

product_ref_id IN ('10', '12')

or

product_ref_id IN (10, 12)

using Zend DB prepared statements so I can fetch all rows contained inside the product id array?

回答1:

Don't implode the array, just pass it:

->where('product_ref_id IN (?)', $product_ids);


回答2:

It is worth mentioned that there is 2 ways to use WHERE IN clausule in Zend_Db_Select:

  1. We can pass array as second parameter:

    $select->where("column_value IN (?)", $array_of_values)

  2. Or we can simply implode array to get values as string:

    $select->where("column_value IN (" . implode(',', $array_of_values) . ")")



回答3:

->where('country_id IN (?)', $country_ids);