Backend Development 9 min read

Building a Simple Shopping Cart with PHP and Vue.js

This tutorial demonstrates how to create a basic shopping cart system by setting up a MySQL database, implementing backend PHP scripts for CRUD operations, and integrating a Vue.js front‑end with Axios to manage products and cart interactions in a full‑stack web application.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Building a Simple Shopping Cart with PHP and Vue.js

The article explains how to develop a common shopping‑cart feature using PHP for the backend and Vue.js for the frontend, covering database design, server‑side logic, and client‑side interaction.

First, a MySQL database named cart is created with two tables: orders for storing user orders and products for product information.

<code>CREATE DATABASE cart;

USE cart;

CREATE TABLE orders(
  id INT PRIMARY KEY AUTO_INCREMENT,
  user_id INT,
  product_id INT,
  quantity INT,
  price DECIMAL(10,2),
  total DECIMAL(10,2)
);

CREATE TABLE products(
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255),
  price DECIMAL(10,2)
);
</code>

A PHP file db_connect.php is provided to establish a MySQL connection:

<code>&lt;?php
$hostname = "localhost";
$username = "your_username";
$password = "your_password";
$database = "cart";

$conn = new mysqli($hostname, $username, $password, $database);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?&gt;
</code>

Four PHP scripts handle cart operations:

add_to_cart.php inserts a new order record based on posted product ID and quantity.

get_cart.php retrieves the current user's cart items using an INNER JOIN between orders and products .

update_cart.php updates the quantity of an existing order.

delete_from_cart.php removes an order from the cart.

<code>&lt;?php
require 'db_connect.php';
// add_to_cart.php example
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
$sql = "SELECT * FROM products WHERE id = $product_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$price = $row['price'];
$total = $price * $quantity;
$sql = "INSERT INTO orders (user_id, product_id, quantity, price, total) VALUES (1, $product_id, $quantity, $price, $total)";
if ($conn->query($sql) === TRUE) {
  echo "Product added to cart successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?&gt;
</code>

On the client side, an index.html file sets up Vue.js and Axios, defines a Vue instance with products and cart arrays, and implements methods to fetch products, add items, retrieve the cart, update quantities, and delete items.

<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Shopping Cart Example&lt;/title&gt;
  &lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt;
  &lt;script src="https://unpkg.com/axios/dist/axios.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div id="app"&gt;
    &lt;h2&gt;Products:&lt;/h2&gt;
    &lt;ul&gt;
      &lt;li v-for="product in products" :key="product.id"&gt;
        {{ product.name }} - ${{ product.price }}
        &lt;input type="number" v-model="product.quantity" min="1" max="10"&gt;
        &lt;button @click="addToCart(product.id, product.quantity)"&gt;Add to Cart&lt;/button&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;h2&gt;Cart:&lt;/h2&gt;
    &lt;ul&gt;
      &lt;li v-for="order in cart" :key="order.id"&gt;
        {{ order.name }} - ${{ order.total }}
        &lt;input type="number" v-model="order.quantity" min="1" max="10"&gt;
        &lt;button @click="updateCart(order.id, order.quantity)"&gt;Update&lt;/button&gt;
        &lt;button @click="deleteFromCart(order.id)"&gt;Delete&lt;/button&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  &lt;script&gt;
    new Vue({
      el: '#app',
      data: { products: [], cart: [] },
      mounted() { this.getProducts(); this.getCart(); },
      methods: {
        getProducts() {
          axios.get('get_products.php')
            .then(response => { this.products = response.data; })
            .catch(error => { console.log(error); });
        },
        addToCart(product_id, quantity) {
          axios.post('add_to_cart.php', { product_id, quantity })
            .then(response => { console.log(response.data); this.getCart(); })
            .catch(error => { console.log(error); });
        },
        getCart() {
          axios.get('get_cart.php')
            .then(response => { this.cart = response.data; })
            .catch(error => { console.log(error); });
        },
        updateCart(order_id, quantity) {
          axios.post('update_cart.php', { order_id, quantity })
            .then(response => { console.log(response.data); this.getCart(); })
            .catch(error => { console.log(error); });
        },
        deleteFromCart(order_id) {
          axios.post('delete_from_cart.php', { order_id })
            .then(response => { console.log(response.data); this.getCart(); })
            .catch(error => { console.log(error); });
        }
      }
    });
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>

The guide concludes that the provided code offers a simplified example of integrating PHP and Vue.js to build a functional shopping cart, and it may require further adjustments for production use.

MySQLVue.jsshopping cartAJAXweb-development
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.