私はミニショッピングカートに取り組んでいます。すべてが機能しているように見えますが、たとえば別の製品をクリックすると、適切なデータが抽出されません。
製品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);