- Making a shopping cart system with PHP 7.4 and MySQL
- Product detail page and add to cart form
- Adding to the cart
- Cart page and checkout
- Cart item removal
- Cart items display
- How to Create a Simple Shopping Cart in PHP 2022
- What are the features of PHP Shopping Cart Source Code?
- Let’s begin to write PHP Code for Shopping Cart System:
- Conclusion
Making a shopping cart system with PHP 7.4 and MySQL
This code example is just a demo to show what is possible, and should not be used for actual e-commerce websites. let’s assume that you already have a product page and are displaying these products from a MySQL database, and now you want to make a cart system so a user can purchase more than one item at a time.
Product detail page and add to cart form
This page show and individual item from the products page and will contain a form to add this item to the cart of the website. This form will go to an addtocart.php file that will set the cookie for the cart. The form will look something like the below code. The ID for this form would have been grabbed from a MySQL database.
print(" $id' method='post'> ");
Adding to the cart
Now for the addtocart.php file. For this page, you will want to connect your MySQL server to get the items from the database to add to the cart. You will also want to make sure that you tell PHP that you want to start using sessions with the session start function.
$server = "localhost"; $username = "username"; $password = "123456789"; $database = "e-commerce"; $connection = mysqli_connect($server, $username, $password, $database); /* And just in case something goes wrong */ if(!$connection) die("Connection Failed: " . mysqli_connect_error()); >
Once you have connected to the server we can add the item to the session. Because of the detail page form, the URL should look something like this example.com/addtocart.php?id=1 which means we can grab the ID of the item from the current URL. Even though the detail page form has the method of post we can still use GET to grab the id because we added it to the action of the form.
$id = $_GET['id']; // Check if the add to cart button was clicked or someone just wants to load this page. This POST method `add` is from the id of the add to cart button on the detail page. if(isset($_POST['add'])) // Check if there is a session for the cart set already, if not then set one. if(!isset($_SESSION['shoppingcart'])) $_SESSION['shoppingcart'] = []; > $quantity = $_POST['quantity']; $item = [ "id" => $id, "quantity" => $quantity ]; // Now add new item to the cart array_push($_SESSION['shoppingcart'], $item); // Once added let's take the user to the cart page header("Location: cart.php"); > else // If the add to cart button was not clicked then go back to the products page. header("Location: products.php"); >
Cart page and checkout
This page will display all of the items in the cart, have a checkout section, and remove all of the cart items.
Cart item removal
To remove all of the items from the cart let’s start with the function that will check if the customer would like to do so and add the form that will trigger this action.
if(isset($_GET['reset'])) session_start(); unset($_SESSION['shoppingcart']); session_destroy(); > // Start the session for the rest of the page after destroying it. session_start();
For the form that will remove all of the items, it would look like this. This form will simply reload this file and add ?reset=RESET to the URL activating the PHP script above to remove the items.
action="#" method="GET"> for="reset">Reset cart: type="submit" value="RESET" name="reset" id="reset" />
Cart items display
// First check if the session is set is(isset($_SESSION['shoppingcart']) && count($_SESSION['shoppingcart'])) $list = $_SESSION['shoppingcart']; foreach($list as $item) $id = $item['id']; // The MySQL database query for the items in the cart. $query = "SELECT * FROM products WHERE "; // The connection variable is taken from the top of the page when we connected to the MySQL database $result = mysqli_query($connection, $query); // If only on item in the database has this id then proceed if(mysqli_num_rows($result) == 1) $row = mysqli_fetch_array($result); $id = $row['id']; $name = $row['name']; $price = $row['price']; $quantity = $item['quantity']; // Now let's print out this item to HTML print( " $id'> $name $$price CAD
Quantity:
$quantity "); > > > else print("You don't have any items in your shopping cart.
"); >
How to Create a Simple Shopping Cart in PHP 2022
The Shopping Add to Cart Script is useful because it allows you to add multiple order products in a single transaction. You will also see here how powerful the functionality of the session.
What are the features of PHP Shopping Cart Source Code?
This PHP Shopping Cart Source Code contains the following features.
-
- Product Listing
- Adding of Products
- Product Updating
- PHP Cart Removing of item.
In this PHP code for shopping cart system, it advised that you will use Twitter Bootstrap templates for you to have a beautiful design.
Let’s begin to write PHP Code for Shopping Cart System:
1. Create a MySQL Database and name it “productdb”.
Note: You can click here MySQL Database if you want to learn more about the database.
2. Execute the query for “add to cart database table” in the MySQL database.
CREATE TABLE IF NOT EXISTS `tblproduct` ( `PRODUCTID` int(11) NOT NULL AUTO_INCREMENT, `MODEL` varchar(30) NOT NULL, `BRAND` varchar(30) NOT NULL, `DESCRIPTION` varchar(99) NOT NULL, `PRICE` double NOT NULL, PRIMARY KEY (`PRODUCTID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
3. Populate the add to cart database table by executing the query below.
INSERT INTO `tblproduct` (`PRODUCTID`, `MODEL`, `BRAND`, `DESCRIPTION`, `PRICE`) VALUES (1, 'HK-LE3212UVP', 'Sharp', 'LCD VIDEO-KARAOKE 32''''', 33298), (2, 'HK-LE1110UVP', 'Sharp', 'LCD VIDEO-KARAOKE 19''''', 22198), (3, '21V-FS720S', 'Sharp', 'Pure Flat TV ', 7190), (4, 'ES-D708', 'Sharp', 'Spin Dryer 7kg ', 4998), (5, 'ES-D958', 'Sharp', 'Spin Dryer 9.5 KG', 5698), (6, 'SJ-DT55AS', 'Sharp', '5.4 CU.FT S/D SEMI AUTO ', 10900);
4. Create a connection between the PHP script and MySQL Database. Name it “config.php”
Note: You can follow the tutorial Connect PHP/MYSQL if you want to have another variation in connecting PHP/MySQL.
$server = ‘localhost’; $dbuser = ‘root’; $dbpass = »; $dbname = ‘productdb’; $con = mysql_connect($server, $dbuser, $dbpass); if (isset($con)) < # code. $dbSelect = mysql_select_db($dbname); if (!$dbSelect) < echo "Problem in selecting database! Please contact administraator"; die(mysql_error()); >> else
5. Create a PHP file called “index.php” for index PHP Cart.
6. Do the following code for the cart list. Name it “cart.php.”
7. Create a PHP file called “process.php” and add the following code for removing of adding and removing of an item in the cart.
if (!empty($_SESSION[‘janobecart’])) < // count the session array varible $max = count($_SESSION['janobecart']); if (!isset($exist))
/* */ alert(‘Item is already in the cart.’) /**/ $_SESSION[‘janobecart’] = array(); $_SESSION[‘janobecart’][0][‘PRODUCTID’] = $pid; $_SESSION[‘janobecart’][0][‘PRICE’] = $price; $_SESSION[‘janobecart’][0][‘QUANTITY’] = 1; > ?>
Note: The code below is a Pop-up Message Using Javascript. This pop-up message is used to display messages about the action of the user, whether successfully executed or not.
/* */ alert('Item has been added in the cart.') /* */ unset($_SESSION['tot']); ?>
/* */ alert('Item has been removed in the cart.') /* redirect to main page.*/ window.location='cart.php' $_SESSION['janobecart'] = array_values($_SESSION['janobecart']); > ?>
Conclusion
In this lesson, we learn how to make add to cart in PHP. Wherein, the output you have done here can be integrated later on to your website. I hope we can hear some feedback from you.