2011-03-11 31 views
1

這裏是我的數組如何使用動態數組中的值來執行sql查詢?

Array 
(
    [0] => 31 
    [1] => 36 
    [2] => 41 
) 

的31,36和41號的記錄的。此數組中的元素可以從1個元素到10個元素的任何位置。表結構看起來像這樣(縮短版)

tbl_cart 
--------- 
id (auto-incremented) 
product_name 
price 

什麼,我試圖找出是我如何做一個查詢,將搶在動態創建陣列聽的ID,然後在積累的價格每個尊敬的id和顯示輸出?

謝謝,讓我知道如果這沒有意義。

回答

1

你想總結清單中的ID的價格吧?

$idStr = implode(',', $arr); 
$sql = "SELECT sum(price) FROM tbl_cart WHERE id in ($idStr)"; 
2

你可以得到的ID作爲使用implode()功能的逗號分隔的字符串,像這樣:

$str_ids = implode(', ', $array); 

然後,你可以注入到這一個SQL查詢,使用in()

select sum(price) as total_price 
from tbl_cart 
where id in ($str_ids) 
+0

謝謝!你救了我這個! – 2013-10-13 13:07:42

0
$vars = array(1, 2, 3, 4); 

$newvars = array(); 

foreach($vars as $var){ 

    if(!empty($var)) 
     $newvars[] = " ID = ".$var; 

} 

$where = join(" OR ", $newvars); 

$sql = "SELECT * FROM table ".(($where)?"WHERE ".$where: null); 

echo $sql; 
0
$ids = implode(',', $array); 
$query = "SELECT id, price FROM tbl_cart WHERE id in ($ids)"; 

$result = mysql_query($query); 

while ($row = mysql_fetch_array($result)) { 
    echo "ID: {$row['id']} Price: {$row['price']}"); 
} 

輸出

// ID: 31 Price: (the price) 
// ID: 36 Price: (the price) 
// ID: 41 Price: (the price)