我試圖從購物車表中獲得總價格。其他表中的product_price是產品。我只得到最新的價格,而不是總價。由於使用pdo的總數列總和
// function total_price(){
$total = 0;
global $db;
$ip = getIp();
$sql = $db->query("SELECT * from cart WHERE ip_add='$ip'");
$no=$sql->rowCount(); // number of rows affected by the last SQL statement
if ($no == 0){
echo "";
} else {
foreach($sql as $row)
$product_id = $row["p_id"];
$sql = $db->query("SELECT product_price from product WHERE product_id='$product_id'");
$no=$sql->rowCount(); // number of rows affected by the last SQL statement
if ($no == 0){
echo "";
}
else
{
foreach($sql as $row)
$product_price = array($row["product_price"]);
$values = array_sum($product_price);
$total += $values;
}
}
echo "RM" . $total;
}
如果你需要的是車中的項目價格的總和,你可以用它做單個查詢 – nogad
'fetch'只拉一行。循環它。另外'ip'對用戶來說並不是唯一的。你也開放SQL注入,參數化。 – chris85