Skip to main content

How to create a simple Shopping App with PHP AJAX MYSQL?

 


Below is the complete code for the PHP, MySQL, and AJAX-based shopping cart application with features like adding products to the cart, updating cart quantities, and checkout with Cash on Delivery (COD). This includes all the necessary files and steps to set up the application.

---




1. Database Setup
Run the following SQL queries to create the database and tables:

```sql
CREATE DATABASE shopping_cart;
USE shopping_cart;

-- Products table
CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    description TEXT,
    image VARCHAR(255)
);

-- Orders table
CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(255) NOT NULL,
    customer_email VARCHAR(255) NOT NULL,
    customer_address TEXT NOT NULL,
    total_amount DECIMAL(10, 2) NOT NULL,
    status ENUM('pending', 'completed') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Order items table
CREATE TABLE order_items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id INT NOT NULL,
    product_id INT NOT NULL,
    quantity INT NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    FOREIGN KEY (order_id) REFERENCES orders(id),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

-- Insert sample products
INSERT INTO products (name, price, description, image) VALUES
('Product 1', 10.00, 'Description for Product 1', 'product1.jpg'),
('Product 2', 20.00, 'Description for Product 2', 'product2.jpg'),
('Product 3', 30.00, 'Description for Product 3', 'product3.jpg');
```

---

2. File Structure
Create the following files in your project directory:

```
shopping_cart/
├── index.php           (Product listing and add to cart)
├── add_to_cart.php     (Add product to cart)
├── get_cart_count.php  (Get cart item count)
├── view_cart.php       (View and update cart)
├── update_cart.php     (Update cart quantities)
├── checkout.php        (Checkout page)
├── place_order.php     (Place order)
└── db.php              (Database connection)
```

---




3. Complete Code
1.db.php


<?php
$conn = new mysqli('localhost', 'root', '', 'shopping_cart');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>




2.index.php


<?php
session_start();
include 'db.php';

// Fetch products
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
$products = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
    <style type="text/css">
        *{
            margin:0;
            padding: 0;
            box-sizing: border-box;
            font-family: sans-serif;
            
        }

          a{
            text-decoration: none;
          }

        .cart-item{
              display: flex;
              
              align-content: center;
              align-items: center;
               width:50px;
               height:50px;
               border-radius:50%;
               background-color:red;
               color: white;
               font-weight: bold;
               text-align: center;
        }


        .container{
            width:100%;
            background-color: whitesmoke;
            display: grid;
            grid-template-columns: repeat(auto-fit,minmax(250px,1fr));
            padding:20px;
            gap: 1rem;
            height:80vh;
        }

        .Items{
            display: flex;
            flex-direction: column;
            height:300px;
/*            border: 1px solid red;*/
            background-color: white;
            padding:1rem;
            justify-content: center;
            align-items: center;
            box-shadow:3px 3px 3px grey;
        }

        .Items button{
               padding:10px;
               background-color:green;
               color: white;
               font-weight: bold;
               border: none;
        }

        .ch{
            text-align: center;
        }

        .Item {
            list-style-type:none;
            padding:5PX;

        }

        .Item li{
             padding:5px;
        }
        
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    
</head>
<body>
    <h1>MyShop</h1>
    <div id="cart-message"></div>
    <div class="cart-item">
    <p>Cart: <span id="cart-count"><?php echo isset($_SESSION['cart']) ? array_sum($_SESSION['cart']) : 0; ?></span></p></div>
    <a href="view_cart.php">View Cart</a>
    <div class="container">
        

    
        <?php foreach ($products as $product): ?>
            <div class="Items">
                <div class="cart-img">
                    <img src="images/<?php echo $product['image']; ?>" alt="img1" width="100%" height="190px">
                   

                 </div>
            <ul class="Item">
            <li>
                <h3><?php echo $product['name']; ?></h3>
                <p><?php echo $product['description']; ?></p>
                <p>Price: $<?php echo $product['price']; ?></p>
                <button onclick="addToCart(<?php echo $product['id']; ?>)">Add to Cart</button>
            </li>
            </ul>
            </div>

        <?php endforeach; ?>
    
   

</div>
 <h1 class="ch"><a href="checkout.php">Proceed to Checkout</a></h1>

    <script>
        function addToCart(productId) {
            $.ajax({
                url: 'add_to_cart.php',
                type: 'POST',
                data: { product_id: productId },
                success: function(response) {
                    $('#cart-message').html(response);
                    // Update cart count
                    $.ajax({
                        url: 'get_cart_count.php',
                        type: 'GET',
                        success: function(count) {
                            $('#cart-count').text(count);
                        }
                    });
                }
            });
        }
    </script>
</body>
</html>

 3.add_to_cart.php


<?php
session_start();

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

$product_id = $_POST['product_id'];
if (isset($_SESSION['cart'][$product_id])) {
    $_SESSION['cart'][$product_id] += 1; // Increase quantity
} else {
    $_SESSION['cart'][$product_id] = 1; // Add new product
}

echo "Product added to cart!";
?>

4. get_cart_count.php
<?php
session_start();
echo isset($_SESSION['cart']) ? array_sum($_SESSION['cart']) : 0;
?>

5.view_cart.php


<?php
session_start();
include 'db.php';

if (empty($_SESSION['cart'])) {
    die("Your cart is empty.");
}

// Fetch cart products
$cart_products = [];
$total_amount = 0;
foreach ($_SESSION['cart'] as $product_id => $quantity) {
    $sql = "SELECT * FROM products WHERE id = $product_id";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $row['quantity'] = $quantity; // Add quantity to product data
        $cart_products[] = $row;
        $total_amount += $row['price'] * $quantity; // Calculate total amount
    }
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Cart</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style type="text/css">
         a{
            text-decoration: none;
            
         }

        
        #cart-form{
               display: flex;
               justify-content: center;
               align-items: center;
               padding:20px;
               flex-direction: column;
        }
        #cart-form table{
             border-collapse: collapse;
             width: 50%;
        }

        .po{
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

         button{
            padding:5px;
            background-color: red;
            color: white;
            font-weight: bold;
            border: none;
         }
    </style>
</head>
<body>
    <h1>Your Cart</h1>
    <form id="cart-form" action="update_cart.php" method="POST">
        <table border="1">
            <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total</th>
            </tr>
            <?php foreach ($cart_products as $product): ?>
                <tr>
                    <td><?php echo $product['name']; ?></td>
                    <td>$<?php echo $product['price']; ?></td>
                    <td>
                        <input type="number" name="quantity[<?php echo $product['id']; ?>]" value="<?php echo $product['quantity']; ?>" min="1">
                    </td>
                    <td>$<?php echo $product['price'] * $product['quantity']; ?></td>
                </tr>
            <?php endforeach; ?>
        </table>
        <br>
        <button type="submit">Update Cart</button>
    </form>
    <br>
    <div class="po">
    <a href="checkout.php">Proceed to Checkout</a>
    <br>
    <a href="index.php">Continue Shopping</a>

   </div>

    <script>
        // Update cart form submission
        $('#cart-form').on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                url: 'update_cart.php',
                type: 'POST',
                data: $(this).serialize(),
                success: function(response) {
                    alert('Cart updated successfully!');
                    location.reload(); // Refresh the page
                }
            });
        });
    </script>
</body>
</html>

6.checkout.php


<?php
session_start();
include 'db.php';

if (empty($_SESSION['cart'])) {
    die("Your cart is empty.");
}

// Fetch cart products
$cart_products = [];
$total_amount = 0;
foreach ($_SESSION['cart'] as $product_id => $quantity) {
    $sql = "SELECT * FROM products WHERE id = $product_id";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $row['quantity'] = $quantity; // Add quantity to product data
        $cart_products[] = $row;
        $total_amount += $row['price'] * $quantity; // Calculate total amount
    }
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout</title>
    <style type="text/css">
        a{
            text-decoration: none;
        }
        .container{
            width:100%;
            min-height:80vh;
            padding:20px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;

        }

        .heading{
            min-height:10vh;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            background-color: whitesmoke;
            color: red;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="heading">
    <h1>Checkout</h1>
    <h2>Your Cart</h2>
</div>
    <ul>
        <?php foreach ($cart_products as $product): ?>
            <div class="Item">
                <div class="cart-img">
                    <img src="images/<?php echo $product['image']; ?>" alt="img1" width="100%" height="190px">
                   

                 </div>
            <li>
                <h3><?php echo $product['name']; ?></h3>
                <p>Price: $<?php echo $product['price']; ?></p>
                <p>Quantity: <?php echo $product['quantity']; ?></p>
                <p>Total: $<?php echo $product['price'] * $product['quantity']; ?></p>
            </li>

        </div>
        <?php endforeach; ?>
    </ul>

    <h2>Total Amount: $<?php echo $total_amount; ?></h2>

    <h2>Customer Details</h2>
    <form action="place_order.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" name="name" required><br><br>
        <label for="email">Email:</label>
        <input type="email" name="email" required><br><br>
        <label for="address">Address:</label>
        <textarea name="address" required></textarea><br><br>
        <input type="submit" value="Place Order (COD)">
    </form>

</div>
</body>
</html>
 
7.place_order.php


<?php
session_start();
include 'db.php';

if (empty($_SESSION['cart'])) {
    die("Your cart is empty.");
}

// Calculate total amount
$total_amount = 0;
foreach ($_SESSION['cart'] as $product_id => $quantity) {
    $sql = "SELECT price FROM products WHERE id = $product_id";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $total_amount += $row['price'] * $quantity;
    }
}

// Insert order
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];

$sql = "INSERT INTO orders (customer_name, customer_email, customer_address, total_amount) 
        VALUES ('$name', '$email', '$address', $total_amount)";
if ($conn->query($sql) === TRUE) {
    $order_id = $conn->insert_id;

    // Insert order items
    foreach ($_SESSION['cart'] as $product_id => $quantity) {
        $sql = "SELECT price FROM products WHERE id = $product_id";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $price = $row['price'];
            $sql = "INSERT INTO order_items (order_id, product_id, quantity, price) 
                    VALUES ($order_id, $product_id, $quantity, $price)";
            $conn->query($sql);
        }
    }

    // Clear cart
    unset($_SESSION['cart']);

    echo "<h1 style='color:red;text-align='center'>Order placed successfully!</h1>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>



Download complete source code:













Comments

Popular posts from this blog

Microsoft Excel top functions.

  Microsoft Excel offers numerous functions to simplify data analysis and calculation. Here are some of the most commonly used and powerful functions: Basic Functions SUM : Adds values. =SUM(A1:A10) AVERAGE : Calculates the mean of numbers. =AVERAGE(A1:A10) IF : Performs logical tests and returns values based on conditions. =IF(A1>10, "Yes", "No") COUNT : Counts numeric values in a range. =COUNT(A1:A10) LEN : Returns the length of a text string. =LEN(A1) Lookup and Reference Functions VLOOKUP : Looks for a value in the first column and returns a value in the same row from another column. =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]) HLOOKUP : Similar to Here are practical examples of common Excel functions and how they can be applied in real-life scenarios: 1. SUM Scenario: Calculate the total sales for a week. Example: A B Day Sales Monday 200 Tuesday 150 Wednesday 300 Thursday 250 Friday 100 ...

Creating Wages Sheet using Microsoft Excel

  Creating wages sheet using Microsoft Excel The DAYS360 function in Microsoft Excel calculates the number of days between two dates based on a 360-day year (commonly used in financial calculations). A 360-day year assumes each month has 30 days, simplifying interest and payment schedules. Syntax: DAYS360(start_date, end_date, [method]) Parameters: start_date : The starting date (required). Enter it as a valid date or reference a cell containing a date. end_date : The ending date (required). Enter it similarly to the start_date. method : Logical value (optional). FALSE (default): Uses the U.S. (NASD) method for date calculations. TRUE : Uses the European method. Key Differences Between Methods: U.S. (NASD) : Adjusts the start and end dates depending on whether they fall on the 31st of a month. European : Always treats the start and end dates as the 30th of the month if they are the 31st. Example Usage: Example 1: Calculate days using the U.S. method =DAYS360("01/01/2024", ...

How to use Microsoft Excel PMT function?

  To use the PMT function in Microsoft Excel, follow these steps: Steps to Use the PMT Function: Open Excel : Open your Excel workbook where you want to calculate the payment. Select a Cell : Click on the cell where you want the result (monthly payment). Enter the PMT Function : Use the formula syntax: =PMT(rate, nper, pv, [fv], [type]) Input Arguments : rate : Interest rate per period (e.g., for a monthly rate, divide the annual rate by 12). nper : Total number of payment periods. pv : Present value (loan amount or investment). fv (optional) : Future value, usually 0 for loans. type (optional) : Payment timing: 0 (default): End of the period. 1: Beginning of the period. Press Enter : Excel will calculate and display the periodic payment. Example 1: Monthly Loan Payment Problem: You take a loan of $15,000 with an annual interest rate of 5%, to be repaid over 3 years (36 months). What is the monthly payment? Steps: Select a cell and enter: =PMT(5%/12, 3*12, -...