Home > Backend Development > PHP Tutorial > How to implement shopping cart function using PHP

How to implement shopping cart function using PHP

PHPz
Release: 2023-08-18 15:36:01
Original
1417 people have browsed it

How to implement shopping cart function using PHP

How to use PHP to implement the shopping cart function

The shopping cart is one of the necessary functions for an online store. Through the shopping cart, customers can add the products they are interested in, view and modify the products and quantities at any time, and finally make a purchase. This article will introduce how to use PHP to implement a simple shopping cart function.

  1. Create database table
    First, we need to create a database table to store the product information of the shopping cart. We can create a table named "cart", including the following fields:
  2. id: auto-increment primary key
  3. product_id: product ID
  4. product_name: product name
  5. product_price: Product price
  6. quantity: Product quantity

You can use the following SQL command to create the table:

CREATE TABLE cart (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    product_id INT(11),
    product_name VARCHAR(255),
    product_price DECIMAL(10, 2),
    quantity INT(11)
);
Copy after login
  1. Add products to Shopping Cart
    First, we need a page to display the product list, and the user can select the products to add to the shopping cart. On the product list page, each product should have an "Add to Cart" button. When the user clicks the button, we need to add the product information to the shopping cart.
<?php
session_start();

// 检查是否已经登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取商品信息
    $product_id = $_POST['product_id'];
    $product_name = $_POST['product_name'];
    $product_price = $_POST['product_price'];
    $quantity = $_POST['quantity'];

    // 将商品信息添加到购物车
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    $sql = "INSERT INTO cart (product_id, product_name, product_price, quantity) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("isdi", $product_id, $product_name, $product_price, $quantity);
    $stmt->execute();
    
    // 提示用户添加成功
    echo "商品已添加到购物车";
}
?>

<!-- 商品列表 -->
<html>
<head>
    <title>商品列表</title>
</head>
<body>
    <h2>商品列表</h2>
    
    <?php
    // 获取商品列表
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            // 输出商品信息及添加到购物车的表单
            echo "<p>{$row['product_name']}, 价格:{$row['product_price']}</p>";
            echo "<form method='post' action=''>";
            echo "<input type='hidden' name='product_id' value='{$row['product_id']}'>";
            echo "<input type='hidden' name='product_name' value='{$row['product_name']}'>";
            echo "<input type='hidden' name='product_price' value='{$row['product_price']}'>";
            echo "数量: <input type='number' name='quantity' value='1' min='1'>";
            echo "<input type='submit' value='添加到购物车'>";
            echo "</form>";
        }
    }
    ?>
</body>
</html>
Copy after login
  1. View Shopping Cart
    Users can view the contents of the current shopping cart by clicking on a "View Shopping Cart" link. We can query the shopping cart table in the database to obtain all product information and display it on the page.
<?php
session_start();

// 检查是否已经登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
?>

<!-- 购物车列表 -->
<html>
<head>
    <title>购物车</title>
</head>
<body>
    <h2>购物车</h2>
    
    <?php
    // 获取购物车列表
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    $sql = "SELECT * FROM cart";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            // 输出购物车商品信息
            echo "<p>{$row['product_name']}, 价格:{$row['product_price']}, 数量:{$row['quantity']}</p>";
        }
    } else {
        echo "购物车为空";
    }
    ?>
</body>
</html>
Copy after login

The above is a simple example of using PHP to implement the shopping cart function. By creating a shopping cart database table and using PHP code to add and view items, we can easily build a simple shopping cart system. Of course, the actual shopping cart function usually also includes functions such as modifying the quantity of items, deleting items, etc., but this is beyond the scope of this article. Hope this article helps you!

The above is the detailed content of How to implement shopping cart function using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template