Learn step by step: How to build a shopping cart function with PHP and MySQL

PHPz
Release: 2024-03-15 15:22:02
Original
489 people have browsed it

Learn step by step: How to build a shopping cart function with PHP and MySQL

In this article, we will learn step by step how to build a simple shopping cart function using PHP and MySQL. The shopping cart is an indispensable part of an e-commerce website. It allows users to temporarily store the products they want to purchase and add, delete, modify, and check the products. By studying this article, you will learn how to use PHP to process logic and MySQL to store data to implement a complete shopping cart function.

Step 1: Create a database

First, we need to create a database to store product information. Open the MySQL database management tool, create a database named shopping_cart, and create a table named products in it to store product information. Table products can contain the following fields:

  • id: the unique identifier of the product, set as an auto-increment primary key
  • name: Product name
  • price: Product price
  • image: Product image path

Step 2: Create a product page

Next, we need to create a page that displays product information so that users can browse and select products to add to the shopping cart. Create a PHP file named products.php, query the database to obtain all product information, and display it on the page. Each item should contain an "Add to Cart" button that clicks to add the item to your cart.

<?php
// Connect to the database
$conn = new mysqli("localhost", "root", "", "shopping_cart");

//Query the database to obtain product information
$sql = "SELECT * FROM products";
$result = $conn->query($sql);

// Loop through the products and display them on the page
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<div>";
        echo "<h3>".$row['name']."</h3>";
        echo "<img  src='".$row['image']."'    style="max-width:90%"  style="max-width:90%" alt="Learn step by step: How to build a shopping cart function with PHP and MySQL" >";
        echo "<p>Price: $".$row['price']."</p>";
        echo "<a href='add_to_cart.php?id=".$row['id']."'>Add to Cart</a>";
        echo "</div>";
    }
}
?>
Copy after login

Step 3: Process the request to add to the shopping cart

When the user clicks the "Add to Cart" button, add the item to the shopping cart. Create a PHP file named add_to_cart.php to handle the logic of adding items to the shopping cart. In this file, you first receive the unique identifier of the item and then add the item to the shopping cart. The shopping cart can be stored using the $_SESSION variable in PHP.

<?php
session_start();

if(isset($_GET['id'])) {
    $product_id = $_GET['id'];
    
    // Query the database to obtain product information and add it to the shopping cart
    $sql = "SELECT * FROM products WHERE id = $product_id";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        
        // Store product information in the shopping cart
        $_SESSION['cart'][$product_id] = array(
            'name' => $row['name'],
            'price' => $row['price'],
            'image' => $row['image'],
            'quantity' => 1
        );
        
        echo "The item has been successfully added to the shopping cart!";
    } else {
        echo "The product does not exist!";
    }
}
?>
Copy after login

Step 4: Display the shopping cart content and operations

Finally, we need to create a page that displays the shopping cart content and shopping cart operations. Create a PHP file named cart.php. By traversing the product information in the shopping cart, display the name, price, quantity and subtotal of each product, and provide the function of adding, reducing and deleting products. .

<?php
session_start();

if(isset($_SESSION['cart'])) {
    foreach($_SESSION['cart'] as $product_id => $product) {
        echo "<div>";
        echo "<h3>".$product['name']."</h3>";
        echo "<img  src='".$product['image']."'    style="max-width:90%"  style="max-width:90%" alt="Learn step by step: How to build a shopping cart function with PHP and MySQL" >";
        echo "<p>Price: $".$product['price']."</p>";
        echo "<p>Quantity: ".$product['quantity']."</p>";
        echo "<p>Subtotal: $".$product['price'] * $product['quantity']."</p>";
        echo "<a href='remove_from_cart.php?id=".$product_id."'>Remove product</a>";
        echo "</div>";
    }
} else {
    echo "The shopping cart is empty!";
}
?>
Copy after login

Through the above steps, we successfully built a simple shopping cart function, which enables the operations of browsing products, adding to the shopping cart, and managing the shopping cart. You can further expand and improve this shopping cart function according to actual needs to make it more complete and practical. I hope this article can be helpful to you, and happy programming!

The above is the detailed content of Learn step by step: How to build a shopping cart function with PHP and MySQL. 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