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.
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><?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);
}
?>
</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><?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();
?>
</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><!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Example</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h2>Products:</h2>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - ${{ product.price }}
<input type="number" v-model="product.quantity" min="1" max="10">
<button @click="addToCart(product.id, product.quantity)">Add to Cart</button>
</li>
</ul>
<h2>Cart:</h2>
<ul>
<li v-for="order in cart" :key="order.id">
{{ order.name }} - ${{ order.total }}
<input type="number" v-model="order.quantity" min="1" max="10">
<button @click="updateCart(order.id, order.quantity)">Update</button>
<button @click="deleteFromCart(order.id)">Delete</button>
</li>
</ul>
</div>
<script>
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); });
}
}
});
</script>
</body>
</html>
</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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.