使用php获取购物车中物品的总成本
我有两个名为使用php获取购物车中物品的总成本,php,mysql,html,Php,Mysql,Html,我有两个名为products和cart的sql表。 在产品中包含所有产品详细信息的表中。 在cart表中,仅包含userID和productID 我想显示购物车中所有项目的总成本。我尝试了这两个函数,但我得到了错误 以下是我的职能: function totalPrice($user){ $cost = 0; $query = "SELECT item_id FROM cart WHERE user_id='".$user."'"; $result = mysql_qu
products
和cart
的sql
表。
在产品中
包含所有产品详细信息的表中。
在cart
表中,仅包含userID
和productID
我想显示购物车中所有项目的总成本。我尝试了这两个函数,但我得到了错误
以下是我的职能:
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($\u 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'];
}
$user变量是否已设置?是否已设置
$item\u id
并且是否确定第二个查询有任何结果?$user\u id已设置。第二个查询有两个results@Peter:抱歉,我复制代码时出错。不要像那样链接数据库调用。永远不要假设DB调用会成功。如果查询失败,它将返回boolean FALSE(不是语句句柄),然后“outer”函数将开始抛出错误。总是假设失败,检查失败,把成功当作惊喜。从技术上讲,你的代码是丰富的。为什么不使用一个join
ed查询,这样您就不需要在子函数中运行查询了?很抱歉,复制代码时出错了。代码在我的real function中已经像您的答案了file@OP对不起,真的搞砸了。它应该是这样工作的