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

How to implement a simple shopping cart function using PHP

WBOY
Release: 2023-09-24 09:36:01
Original
2115 people have browsed it

How to implement a simple shopping cart function using PHP

How to use PHP to implement a simple shopping cart function

The shopping cart function is an essential part of an e-commerce website, which allows users to place items they are interested in Add to cart, then proceed to checkout or continue browsing and adding items. This article will introduce how to use PHP to implement a simple shopping cart function and provide specific code examples.

  1. Create database and tables

First, we need to create a database and a table for storing shopping cart data.

CREATE DATABASE shopping_cart;
USE shopping_cart;

CREATE TABLE cart(
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(50),
    price DECIMAL(10,2),
    quantity INT,
    total DECIMAL(10,2)
);
Copy after login
  1. Create a product list page

Next, we need to create a product list page where users can select products to add to their shopping cart. The following is a simple sample code:

<?php
// 连接数据库
$connection = mysqli_connect("localhost", "username", "password", "shopping_cart");

// 查询所有商品
$query = "SELECT * FROM products";
$result = mysqli_query($connection, $query);

// 遍历商品并显示在页面上
while($row = mysqli_fetch_assoc($result)) {
    echo "<h3>".$row['product_name']."</h3>";
    echo "<p>价格:".$row['price']."</p>";
    echo "<button onclick='addToCart(".$row['id'].")'>添加到购物车</button>";
}

// 关闭数据库连接
mysqli_close($connection);
?>

<script>
function addToCart(productId) {
    // 向后端发送请求,将商品添加到购物车
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "add_to_cart.php", true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            alert("商品已添加到购物车!");
        }
    };
    xhr.send("productId=" + productId);
}
</script>
Copy after login
  1. Create the backend code for adding items to the shopping cart

In the previous step, we called a function called ## The back-end script of #add_to_cart.php is used to add selected items to the shopping cart. Here is the sample code for the script:

<?php
// 获取待添加到购物车的商品ID
$productId = $_POST['productId'];

// 根据商品ID查询商品信息
$connection = mysqli_connect("localhost", "username", "password", "shopping_cart");
$query = "SELECT * FROM products WHERE id = '".$productId."'";
$result = mysqli_query($connection, $query);
$product = mysqli_fetch_assoc($result);

// 添加商品到购物车表格中
$insertQuery = "INSERT INTO cart (product_name, price, quantity, total) 
                VALUES ('".$product['product_name']."', '".$product['price']."', 1, '".$product['price']."')";
mysqli_query($connection, $insertQuery);

// 关闭数据库连接
mysqli_close($connection);
?>
Copy after login

    Create a shopping cart page
Finally, we need to create a shopping cart page that displays the items the user has added to the shopping cart and calculate the total amount. The following is an example of a simple shopping cart page:

<?php
$connection = mysqli_connect("localhost", "username", "password", "shopping_cart");

$query = "SELECT * FROM cart";
$result = mysqli_query($connection, $query);

$totalPrice = 0;

while($row = mysqli_fetch_assoc($result)) {
    echo "<h3>".$row['product_name']."</h3>";
    echo "<p>价格:".$row['price']."</p>";
    echo "<p>数量:".$row['quantity']."</p>";
    echo "<hr>";
    // 计算总金额
    $totalPrice += $row['total'];
}

echo "<h4>总金额:".$totalPrice."</h4>";

mysqli_close($connection);
?>
Copy after login
So far, we have successfully implemented a simple shopping cart function. Users can select products on the product list page and add them to the shopping cart, and then view the added products and calculate the total amount on the shopping cart page.

It should be noted that this article only provides a basic implementation example. In actual applications, it may be necessary to handle more complex functions such as increasing or decreasing the number of products, deleting products, and user login. Additionally, proper data validation and optimization are required to ensure security and performance.

I hope this article can be helpful to beginners and provide you with some ideas and references in practical applications.

The above is the detailed content of How to implement a simple 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