Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do MySQL IN clauses using Zend DB?

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?

like image 311
danronmoon Avatar asked Dec 30 '11 18:12

danronmoon


2 Answers

Don't implode the array, just pass it:

->where('product_ref_id IN (?)', $product_ids);
like image 172
ben Avatar answered Nov 15 '22 10:11

ben


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) . ")")

like image 45
M. Hryszczyk Avatar answered Nov 15 '22 11:11

M. Hryszczyk