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

Creating a Student Marksheet using Microsoft Excel.

 Creating a Student Marksheet using Microsoft Excel.  Creating a student marks sheet in MS Excel is straightforward. Here's a step-by-step guide to design one: Step 1: Open MS Excel Launch MS Excel and open a new workbook. Step 2: Structure the Sheet Header Section: Use the first few rows to include the title, such as "Student Marks Sheet" and relevant details like the class, semester, or term. Column Headings: In Row 5 (or below the title), define your column headers: Column A: Roll Number Column B: Student Name Column C onward: Subjects (e.g., Mathematics, Science, English, etc.) Final Columns: Include Total Marks , Percentage , and Grade . Example: Roll No.Student Name Mathematics Science English Total Marks Percentage Grade Step 3: Input Data Enter the roll numbers, student names, and their marks under respective columns. Step 4: Add Formulas Total Marks: In the "Total Marks" column, use the formula to sum marks: =SUM(C2:E2) Copy this ...

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

What is Kruti Dev and how to download ?

  Kruti Dev is a popular typeface or font used primarily for typing in the Devanagari script, which is the script for Hindi, Marathi, and other Indian languages. It is widely used in government offices, printing presses, and other organizations in India for Hindi typing. Key Features of Kruti Dev: It is a non-Unicode font, meaning it does not follow the modern Unicode standard. Instead, it uses legacy encoding, which is different from Unicode fonts like Mangal. Kruti Dev fonts are available in various styles and sizes (e.g., Kruti Dev 010, Kruti Dev 020). It requires specific software or a keyboard layout to type effectively. How to Download Kruti Dev Font Official Sources: The font can often be downloaded from trusted websites offering Hindi typing tools or fonts. Ensure the site is reputable to avoid downloading malicious software. Steps to Download: Search for "Download Kruti Dev font" online. Visit a trusted source, such as: www.indiatyping.com www....