使用 php 获取购物车中商品的总成本

get total cost for items in cart with php

我有两个 sql table,名为 productscart。 在 products table 中包含所有产品详细信息。 在 cart table 中仅包含 userIDproductID

我想显示购物车中所有商品的总费用。我尝试使用这两个函数,但出现错误。

这些是我的功能:

function totalPrice($user){
    $cost = 0;
    $query = "SELECT item_id FROM cart WHERE user_id='".$user."'";

    $result = mysql_query($query) or die(mysql_error());

    while($itemid = mysql_fetch_array($result)) {
        $iprice = getProductPrice($itemid);
        $cost += $iprice;
    }

    return $cost;
}

function getProductPrice($item_id){
    $query = "SELECT product_price FROM products WHERE product_id='".$item_id."'";

    $result = mysql_result(mysql_query($query), 0);

    return $result;
}

当我调用 totalPrice($_SESSION['user']) 时,出现此错误

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 23 in C:\xampp\htdocs\s\product\includes\cartprocess.php on line 50

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 24 in C:\xampp\htdocs\s\product\includes\cartprocess.php on line 50

如何通过小修改解决这个问题??

将您的 while 循环更改为:

while ($itemid = mysql_fetch_array($result)) {
    $iprice = getProductPrice($itemid);
    $cost += $iprice;
}

我也想把你的功能改成:

function getProductPrice($item_id){
    $query = "SELECT product_price FROM products WHERE product_id='".$item_id."' LIMIT 1";

    $result = mysql_fetch_assoc(mysql_query($query));

    return $result['product_price'];
}