In e-commerce, SKU (Stock Keeping Unit) is used to identify and manage individual products in inventory. Implementing SKU functionality allows merchants to manage product stock and sales more efficiently, and helps customers choose and purchase items more conveniently. This article demonstrates how to implement SKU functionality in an e-commerce store using a simple PHP example.
First, we need to create two tables: one to store product information and another to store SKU details.
CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `price` DECIMAL(10,2) NOT NULL, `description` TEXT, PRIMARY KEY (`id`) );
CREATE TABLE `skus` ( `id` int(11) NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL, `size` VARCHAR(50) NOT NULL, `color` VARCHAR(50) NOT NULL, `stock` int(11) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE );
Next, we will show how to use PHP to connect to the database and handle SKU-related functionalities.
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
function getProducts() { global $conn; $sql = "SELECT * FROM products"; $result = $conn->query($sql); if ($result->num_rows > 0) { $products = array(); while($row = $result->fetch_assoc()) { $products[] = $row; } return $products; } else { return null; } }
function getSkusByProduct($product_id) { global $conn; $sql = "SELECT * FROM skus WHERE product_id = $product_id"; $result = $conn->query($sql); if ($result->num_rows > 0) { $skus = array(); while($row = $result->fetch_assoc()) { $skus[] = $row; } return $skus; } else { return null; } }
function updateStock($sku_id, $quantity) { global $conn; $sql = "UPDATE skus SET stock = stock - $quantity WHERE id = $sku_id"; $conn->query($sql); }
function addSku($product_id, $size, $color, $stock) { global $conn; $sql = "INSERT INTO skus (product_id, size, color, stock) VALUES ($product_id, '$size', '$color', $stock)"; $conn->query($sql); }
With the code examples above, we have demonstrated how to implement SKU functionality in an e-commerce store using PHP. Developers can further expand and optimize this functionality based on their specific requirements. We hope this example helps you understand how to efficiently manage product inventory using PHP in an e-commerce platform.