我正在做一个迷你购物车。一切似乎都有效,但是,当我单击不同的产品时,它不会提取正确的数据,例如
我选择产品 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);