我创建了两个php代码,一个用于将产品添加到购物车,另一个PHP代码是从购物车中删除产品。但是我只是想知道我是否需要在产品表附近使用html创建一个按钮,以便用户能够从篮子中添加或移除产品。
<?php
session_start();
// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart_items'])){
$_SESSION['cart_items'] = array();
}
// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}
// else, add the item to the array
else{
$_SESSION['cart_items'][$id]=$name;
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>
答案 0 :(得分:0)
您只提供PHP代码。如果你想在前端使用它 - 你需要创建链接,表单,ajax。
链接
<a href="yourcode.php?id=ID&name=NAME&quantity=QUANTITY">
形式
<form action="yourcode.php">
<input type="hidden" name="id" value="ID">
<input type="hidden" name="name" value="NAME">
<input type="text" name="quantity" value="1">
<input type="submit" value="Add or Delete">
</form>
ajax(jquery)。对于ajax,您需要返回json响应为{success:true,message:&#34; Product已添加到购物车&#34;}您也可以使用$ .ajax而不是$ .get。
$.get('yourcode.php', {id: 'ID', name: 'NAME', quantity: 'QUANTITY'},
function (response) {
if (response.success && response.message) {
alert(response.message);
} else {
alert('Something went wrong');
}
}
);