Add to Cart using PHP and MySQL

Add to Cart using PHP and MySQL

If you are building an e-commerce or product-based web application in PHP and MySQL. And in this application, you have to implement shopping add to cart functionality with ajax using PHP and MySQL. So that any user can easily add the product and item to the cart by using it.

PHP MySQL Ajax add to cart; Throughout this tutorial, you will learn how to create online shopping add to cart functionality in PHP Mysql Ajax. And also, you can use and modify the free source code of simple online shopping add to cart with ajax using PHP and MySQL.

Add to Cart with Ajax using PHP and MySQL

Steps to create simple online shopping add to cart functionality with ajax using PHP and MySQL:

  • Step 1: Create a Database and Tables
  • Step 2: Setting up the Database
  • Step 3: Create add_to_cart PHP File
  • Step 4: Create an Index File
  • Step 5: Create get_cart_item_count
  • Step 6: Testing the “Add to Cart” Functionality

Step 1: Create a Database and Tables

First of all, open your phpmyadmin and execute the following SQL queries to create database and tables for your shopping cart add to functionality in php mysql ajax:

CREATE DATABASE DEMO;

CREATE TABLE products (
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  price DECIMAL(10, 2) NOT NULL
);

CREATE TABLE cart (
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  product_id INT(11) NOT NULL,
  quantity INT(11) NOT NULL DEFAULT 1
);

Step 2: Setting up the Database

Once you have created a database and table, now you need to setup a database with your application. So, create a database.php file and add the following code to it:

<?php
// Database configuration
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';

// Create a database connection
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Step 3: Create add_to_cart PHP File

Next, you need to create add to cart functionality to add items in the shopping cart with ajax using php and mysql, to update quantity and save orders. So create an add_to_cart.php file and add the following code to it:

<?php
require_once 'database.php';

// Retrieve the product ID from the AJAX request
$productId = $_POST['id'];

// Check if the product exists
$sql = "SELECT * FROM products WHERE id = $productId";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Insert the product into the cart
  $insertSql = "INSERT INTO cart (product_id) VALUES ($productId)";
  
  if ($conn->query($insertSql) === TRUE) {
    echo json_encode(['success' => true, 'message' => 'Product added to cart successfully.']);
  } else {
    echo json_encode(['success' => false, 'message' => 'Failed to add product to cart.']);
  }
} else {
  echo json_encode(['success' => false, 'message' => 'Product not found.']);
}

Step 4: Create an Index File

Now, you need to create index.php to retrieve/get and display products on a web page with add to cart button. So, Create an HTML file with a form to display the products and allow the user to add them to the cart. Here’s a code of the php, jquery, ajax and HTML markup:

<!DOCTYPE html>
<html>
<head>
  <title>Add to Cart</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      // AJAX function to handle adding items to the cart
      $('.add-to-cart-btn').click(function() {
        var productId = $(this).data('id');
        
        $.ajax({
          url: 'add_to_cart.php',
          method: 'POST',
          data: {id: productId},
          success: function(response) {
            // Handle the response
            if (response.success) {
              alert(response.message);
              // Reload the cart item count
              loadCartItemCount();
            } else {
              alert('An error occurred: ' + response.message);
            }
          },
          error: function() {
            alert('An error occurred while processing the request.');
          }
        });
      });

      // Load the initial cart item count
      loadCartItemCount();
    });

    // AJAX function to load the cart item count
    function loadCartItemCount() {
      $.ajax({
        url: 'get_cart_item_count.php',
        method: 'GET',
        success: function(response) {
          // Update the cart item count
          $('#cart-item-count').text(response);
        },
        error: function() {
          alert('An error occurred while loading the cart item count.');
        }
      });
    }
  </script>
</head>
<body>
  <h1>Add to Cart</h1>
  
  <div id="products">
    <!-- Fetch and display the products using PHP -->
    <?php
    require_once 'database.php';

    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
        $productId = $row['id'];
        $productName = $row['name'];
        $productPrice = $row['price'];

        echo '<div>';
        echo '<span>' . $productName . ' - $' . $productPrice . '</span>';
        echo '<button class="add-to-cart-btn" data-id="' . $productId . '">Add to Cart</button>';
        echo '</div>';
      }
    } else {
      echo 'No products found.';
    }
    ?>
  </div>
  
  <div id="cart">
    <h2>Cart</h2>
    <p>Item count: <span id="cart-item-count">0</span></p>
  </div>
</body>
</html>

Step 5: Create get_cart_item_count

Now, create get_cart_item_count.php to retrieve the total count of items added to the cart:

<?php
require_once 'database.php';

// Retrieve the cart item count
$sql = "SELECT COUNT(*) AS item_count FROM cart";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  $row = $result->fetch_assoc();
  $itemCount = $row['item_count'];
  
  echo $itemCount;
} else {
  echo '0';
}

Step 6: Testing the “Add to Cart” Functionality

Finally, Open the HTML file in a web browser. You should see a list of products with “Add to Cart” buttons next to each product.

Conclusion

That’s it! You have successfully learned how to create an “Add to Cart” functionality with ajax using PHP and MySQL.

Recommended Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *