How to make a pHP basket

Make a dynamic shopping cart with PHP: learn how to create a functional cart with a step-by-step example.

Creating a PHP Shopping Basket

The following is an example of how to create a basic shopping basket from scratch using PHP and MySQL. This tutorial assumes that you have a basic understanding of PHP, MySQL and HTML.

The first step is to create a database table to store the items in the basket. This table should include a unique identifier for each item, the item name, the quantity of the item, the price of the item, and any other relevant information.


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

Once the table is created, we need to write the code to add items to the basket. This code should take the item name and quantity as parameters, query the database to get the price of the item and then insert the item into the basket table.


$itemName = $_POST['itemName'];
$quantity = $_POST['quantity'];

$getPriceQuery = "SELECT price FROM items WHERE name = '$itemName'";
$getPriceResult = mysqli_query($connection, $getPriceQuery);
$itemPrice = mysqli_fetch_assoc($getPriceResult)['price'];

$addToBasketQuery = "INSERT INTO basket (name, quantity, price) VALUES ('$itemName', '$quantity', '$itemPrice')";
mysqli_query($connection, $addToBasketQuery);

Next, we need to write code to retrieve the items from the basket. This code should query the database for all items in the basket and then loop through the results to display them.


$getBasketQuery = "SELECT * FROM basket";
$getBasketResult = mysqli_query($connection, $getBasketQuery);

while ($item = mysqli_fetch_assoc($getBasketResult)) {
	echo "Item Name: " . $item['name'] . " Quantity: " . $item['quantity'] . " Price: " . $item['price'] . "<br>";
}

Finally, we need to write code to calculate the total cost of the items in the basket. This code should query the database for all items in the basket, loop through the results and add up the total cost.


$getTotalQuery = "SELECT SUM(price * quantity) AS total FROM basket";
$getTotalResult = mysqli_query($connection, $getTotalQuery);
$total = mysqli_fetch_assoc($getTotalResult)['total'];

echo "Your total cost is: " . $total;

This tutorial has shown how to create a basic shopping basket from scratch using PHP and MySQL. The code snippets provided should provide a starting point for building a more complex shopping basket.

Answers (0)