3

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

$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 的数组,而不是一个静态的。IE:

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

这可能吗?

4

4 回答 4

7

您可以将数组转换为字符串并在查询中使用它。请注意,以下假设 $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");
于 2013-09-20T12:55:05.833 回答
2

您可以使用IN子句。

WHERE pc.category_id in (2, 6, 22, 33, 34, 83, 220, 222, 886, 897);
于 2013-09-20T12:55:32.937 回答
1

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

您可以使用array_walkPHP 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)";
于 2013-09-20T13:09:53.010 回答
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");
于 2013-09-20T13:03:32.717 回答