Foreach循环mysql查询

时间:2019-01-23 14:12:10

标签: php

我有这样的数组

Array
(
[0] => 149
[1] => 150
)

如何进行foreach循环和查询? 我喜欢每个$ value匹配结果并返回

$damasks = $cart['damask_id']; //array data
            foreach ($damasks as $key => $value) {

            }

完整示例:

foreach ($damasks as $key => $value) 
{ 
    $damask_query = $this->db->query("
        SELECT oc_damask_name.name 
        FROM " . DB_PREFIX . "cart 
        LEFT JOIN oc_damask_frontend ON ( $value = oc_damask_frontend.damask_id) 
        LEFT JOIN oc_damask_name ON ( oc_damask_frontend.damask_id = oc_damask_name.id ) WHERE api_id = '" . (isset($this->session->data['api_id']) ? (int)$this->session->data['api_id'] : 0) . "' 
        AND customer_id = '" . (int)$this->customer->getId() . "' 
        AND session_id = '" . $this->db->escape($this->session->getId()) . "'"); 
}

1 个答案:

答案 0 :(得分:1)

根据您的示例和注释,您没有将数据存储到array中并在循环外打印,这只会打印最后一个索引。

您需要将结果存储到类似$damask_query[]

的数组中

示例:

$damask_query = array(); // initialize
foreach ($damasks as $key => $value) 
{ 
    $damask_query[] = $this->db->query(" // change in this line
        SELECT oc_damask_name.name 
        FROM " . DB_PREFIX . "cart 
        LEFT JOIN oc_damask_frontend ON ( $value = oc_damask_frontend.damask_id) 
        LEFT JOIN oc_damask_name ON ( oc_damask_frontend.damask_id = oc_damask_name.id ) WHERE api_id = '" . (isset($this->session->data['api_id']) ? (int)$this->session->data['api_id'] : 0) . "' 
        AND customer_id = '" . (int)$this->customer->getId() . "' 
        AND session_id = '" . $this->db->escape($this->session->getId()) . "'"); 
}

print_r($damask_query); // will print multiple records store in array.