2017-01-10 127 views
-3

我試圖從購物車表中獲得總價格。其他表中的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; 

     } 
+0

如果你需要的是車中的項目價格的總和,你可以用它做單個查詢 – nogad

+0

'fetch'只拉一行。循環它。另外'ip'對用戶來說並不是唯一的。你也開放SQL注入,參數化。 – chris85

回答

1

如果我讀的結構權這一個查詢應該是所有您需要:

select sum(product_price) from product 
inner join cart on product.product_id=cart.product_id 
+0

我更改爲此代碼,但總價格函數total_price(){ global $ db; $ ip = getIp(); $查詢= $ DB->製備(」 SELECT SUM(p.product_price * c.quantity)AS總FROM購物車爲C JOIN產物爲P ON p.product_id = c.p_id WHERE c.ip_add =: ip '); $ query-> bindParam(':ip',$ ip); $ query-> execute(); $ row = $ query-> fetch(PDO :: FETCH_ASSOC);如果($ row){ $ total =(float)$ row ['total'];其他{ $ total = 0; } return $ total; } – linda