如何使用html和php创建按钮


how to create a button using html and 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);
}
?>

您只提供php代码。如果你想在前端使用它,你需要创建链接、表单和ajax。

  1. 链路

    <a href="yourcode.php?id=ID&name=NAME&quantity=QUANTITY">

  2. 形成

    <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>

  3. ajax(jquery)。对于ajax,您需要将json响应返回为{success:true,消息:"Product has been added to the cart"},也可以使用$.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'); } } );