我正在学习如何使用这个StackOverflow,所以请耐心等待。如果你还需要什么,我可以提供。如果你能帮助我,我可以点击你答案的复选标记。
我的代码正在运行,但有一个小问题。目前,我有$ 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的项目。
答案 0 :(得分:0)
不应将index_to_remove
设置为$i
,而应将其设置为$item_id
和会话变量。这样,您就不再需要$i
。
此外,此行还会为您留下SQL注入漏洞:$item_id = $each_item['item_id'];
。你应该至少使用mysqli_real_escape_string()
来逃避它。