我剛剛學習如何使用此StackOverflow,因此請耐心等待。如果你需要更多的東西,我可以提供。如果你能幫助我,我可以點擊答案上的複選標記。使用PHP和MySQL從我的購物車中刪除項目
我的代碼正在工作,但有一個小故障。目前,我有$ i = 0,我的代碼從表單中刪除$ i。問題是,例如,當刪除$ i = 2時,$ i = 3變爲$ i = 2,並且我不能再從我的購物車中刪除該項目,因爲它現在與刪除的$ i相同。
這裏是我的代碼:
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
header("location: cart.php");
} else {
unset($_SESSION["cart_array"]["$key_to_remove"]);
//sort($_SESSION["cart_array"]);
}
}
這裏是我的輸出循環:
$cartoutput = "";
$cartTotal="";
$totalwithtaxdisplay = 0;
$servicechargedisplay =0;
$grandtotaldisplay = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<div align='center'><font style='font-weight: bold; font-size: 20pt;'>Your order is currently empty.</font></div>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//echo mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
//item id is $each_item['item_id']; being pulled in from form on other page PID.
$id = $row['id'];
$product_name = $row["name"];
$price = $row["price"];
$description = $row['description'];
}
$tax = .065;
$service = .18;
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$totalwithtax = round($cartTotal + ($cartTotal * $tax), 2); //Order Items + Tax
$totalwithtaxdisplay = number_format($totalwithtax, 2, '.', ''); //displays the decimals correctly
$servicecharge = round($totalwithtax * $service, 2); //service charge
$servicechargedisplay = number_format($servicecharge, 2, '.', ''); //displays the decimals correctly
$grandtotal = round($totalwithtax + ($totalwithtax * $service), 2); //service charge
$grandtotaldisplay = number_format($grandtotal, 2, '.', ''); //displays the decimals correctly
$cartoutput .= " <tr><td width='20%'> Order Item $i </td>
<td width='40%'> " . $product_name . "</td>
<td width='20%'> $" . $price . ".00</td>";
$cartoutput .=" <td width='20%'><form action='cart.php' method='post'>
<input name='deleteBtn" . $item_id . "'type='submit' value='Remove This Item' />
<input name='index_to_remove' type='hidden' value='" . $i . "' />
</form></td></tr>";
$i++;
}
}
我回聲出在稍後的時間$ cartouput。您可以在上面的代碼中看到第二個$ cartouput是我正在使用的表單。它包含值$ i,但是當該值被刪除時,它不會讓我刪除已更新到新$ i的項目。
你可以發佈你的輸出循環嗎? –
你爲什麼從你的代碼中刪除重要的部分? – Cilan
對不起,我試圖正確發佈它。它應該現在更新。 – user3150191