在Mysql查询中使用数组值

时间:2013-09-20 12:49:41

标签: php mysql sql arrays

我有一个查询来根据设置参数选择有限的结果:

$query = $this->db->query ("
    SELECT 
        p.product_id, 
        p.quantity 
    FROM {$this->prefix}product p 
    LEFT JOIN {$this->prefix}product_to_category pc 
        ON (p.product_id = pc.product_id) 
    WHERE pc.category_id = '3' 
    AND p.status = '1' 
    ORDER BY p.quantity DESC 
    LIMIT 0, 4");

这将返回产品category_id = 3的库存量最高的4种产品。

我想让它使用类别id的数组而不是静态数组。即:

$categories = array(2, 6, 22, 33, 34, 83, 220, 222, 886, 897);

这可能吗?

4 个答案:

答案 0 :(得分:6)

您可以将数组转换为字符串并在查询中使用它。请注意,下面假设$ categories已经安全且不包含恶意输入。如果不是这种情况,则需要清理输入。

$categoriesClause = implode(",",$categories);

$query = $this->db->query ("
    SELECT 
        p.product_id, 
        p.quantity 
    FROM {$this->prefix}product p 
    LEFT JOIN {$this->prefix}product_to_category pc 
        ON (p.product_id = pc.product_id) 
    WHERE pc.category_id IN ($categoriesClause)
    AND p.status = '1' 
    ORDER BY p.quantity DESC 
    LIMIT 0, 4");

答案 1 :(得分:1)

您可以使用IN子句。

WHERE pc.category_id in (2, 6, 22, 33, 34, 83, 220, 222, 886, 897);

答案 2 :(得分:1)

如果您的类别是文本而不是数字,则需要先引用它们才能进入查询。

您可以使用array_walk执行此操作,并在PHP 5.3及更高版本上使用匿名回调函数。您也可以继续使用这些值,以便在循环它们时使它们安全:

$categories = array(2, 6, 22, 33, 34, 83, 220, 222, 886, 897);

array_walk($categories, function( &$category ) { 
     $category = $this->db->escape_string($category);
     $category = "'{$category}'";
 });

$categories_inclause = implode(",", $categories);

$this->db->query = "SELECT blah WHERE pc.category_id IN ($categories_inclause)";

答案 3 :(得分:0)

IN()implode()结合使用:

$query = $this->db->query ("
SELECT 
    p.product_id, 
    p.quantity 
FROM {$this->prefix}product p 
LEFT JOIN {$this->prefix}product_to_category pc 
    ON (p.product_id = pc.product_id) 
WHERE pc.category_id = IN(" . implode(',', $categories) . ") 
AND p.status = '1' 
ORDER BY p.quantity DESC 
LIMIT 0, 4");