我正在开发一款迷你购物车。一切似乎都有效,但是,当我点击其他产品时,它并没有提取正确的数据。
我选择产品1 - 它为我提供了正确的信息,但如果我选择产品2,它将提供与产品1相同的信息。
我将在下面显示我的代码,但我相信错误来自这行代码:
$sql = sprintf("SELECT Model, Price FROM Bike WHERE BikeCode = %d;", $bikecode);
我认为它没有获得$ bikecode
这是php文件中的整个代码:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT Model, Price FROM Bike WHERE BikeCode = %d;", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity <a href=\"$_SERVER[PHP_SELF]?action=remove&id=$bikecode\">X</a></td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = %d;", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>
非常感谢帮助,但如果您找不到错误,请指导我以另一种方式显示此代码:
$sql = sprintf("SELECT Model, Price FROM Bike WHERE BikeCode = %d;", $bikecode);
答案 0 :(得分:0)
看起来你已经得到了它,但是为了便于引用可能会搜索它的其他人,问题是你在sprintf()中使用%d来尝试表示当%d被视为整数时的varchar。使用%s将解决问题。