functions.php
$conn = mysqli_connect("localhost:3305","root","1234","dj"); //connect database
function getRealIpUser(){
switch(true){
case(!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
case(!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
case(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
default : return $_SERVER['REMOTE_ADDR'];
}
}
cart.php
<include ("functions.php");>
<div class="shopping-cart">
<h6>My Cart</h6>
<hr>
<?php
$ip_add = getRealIpUser(); //getRealIpuser from functions.php
$select_cart = "select * from cart where ip_add='$ip_add'";
$run_cart = mysqli_query($conn,$select_cart);
while($row_cart = mysqli_fetch_array($run_cart)){
$pro_id = $row_cart['p_id'];
$pro_size = $row_cart['size'];
$pro_quantity = $row_cart['quantity'];
?>
<form action="cart.php" method="post" class="cart-items">
<div class="border rounded">
<div class="row bg-white">
<div class="col-md-6">
<button type="submit" class="btn btn-warning">Save for Later</button>
<button type="submit" id="<?php echo $pro_id;?>" class="btn btn-danger mx-2" name="remove">Remove</button>
</div>
</div>
</div>
</form>
然后下面是我的错误的代码:
<?php
global $conn;
if(isset($_POST['remove'])){
$delete_product = "delete from cart where p_id='$pro_id'";
$run_delete = mysqli_query($conn,$delete_product);
if($run_delete){
echo "<script>window.open('cart.php','_self')</script>";
}
}
?>
您需要遍历购物车,并逐个删除相应的产品。在您的cart.php文件中,while循环中的每个表单都应该具有唯一的ID属性,以与每个产品的ID对应。您的删除代码没有传递产品ID,因此无法删除正确的产品。以下是您可以尝试的更新代码:
<?php
if(isset($_POST['remove'])){
global $conn;
$pro_id = $_POST['remove'];
$delete_product = "delete from cart where p_id='$pro_id'";
$run_delete = mysqli_query($conn,$delete_product);
if($run_delete){
echo "<script>window.open('cart.php','_self')</script>";
}
}
?>
请注意,您仍然需要在while循环中的每个表单元素上将产品ID作为ID属性传递,例如:
<button type="submit" id="<?php echo $pro_id;?>" class="btn btn-danger mx-2" name="remove">Remove</button>