- Lesson 20 — E-shop in PHP — Product detail logic
- Database
- Limited offer: Learn all knowledge and save money
- Commercial article (licence no-reselling)
- Article description
- Index php page shop product details
- Products List
- Configuration
- Product List (Index.php)
- Listing Products from Database
- Shopping Cart Box
- Updating Cart
- View Item Summary
- Add a shopping cart to ecommerce website in php
- Cart
Lesson 20 — E-shop in PHP — Product detail logic
In the previous lesson, E-shop in PHP — Finishing the accounting settings, we added accounting settings to the project. Thanks to that, we can now determine things like the VAT rate or whether the seller is a VAT payer. We’ll continue working on products today, specifically, on product details.
Database
Users will be able to write reviews for the products/goods. Reviews will consist of a textual description or critique and a rating based on a particular number of stars (1-5). Let’s prepare the database table for these reviews. The table will have the following columns:
- review_id (int) — Review Id, primary key, autoincrement
- content (text) — Text review
- user_id (int) — User Id, foreign key
- product_id (int) — Product Id, foreign key
- rating (int) — Number of given stars
- sent (datetime) — Date and time of rating submission
. End of the preview.
Continue further
You’ve come here and that’s great! We believe that the first lessons showed you something new and useful
Do you want to continue the course? Go to the premium section.
Limited offer: Learn all knowledge and save money
Before buying this article, you have to buy the previous one
This article is licensed: Premium no-reselling, by buying this article, you agree with the terms of use.
Commercial article (licence no-reselling)
This article is based on many years of experience in the IT field, and describes how to develop a professional commercial product or parts, that can be directly used to generate profit or to get as a gate into the industry.
This knowledge is only for the members of our community who are working their way up to become IT professionals. Therefore, this knowledge is only available in exchange for credits. You can use the source code from this article for one commercial project. However, you will not be able to resell it. Simply put, you can’t buy our article once and then sell our code multiple times. If you need to use this code a bit more extensively, we are ready to discuss Commercial licence options with you. You can find more info on this in the following article Licence.
Are you ready to become a professional? All you have to do is click here!.
Article description
Requested article covers this content:
In this tutorial, we’ll implement the logic needed to add product details and user product reviews. We’ll continue programming our complete e-shop in PHP.
You gain credits by supporting our network. This is done by sending a helpful amount of money to support the site, or by creating content for the network.
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
David learned IT at the Unicorn University — a prestigious college providing education on IT and economics.
Index php page shop product details
Shopping Cart is very important part of any online store, it not only allows user to accumulate list of items for final purchase, but also calculates total amount of all the products. Since my last article on PayPal Express Checkout with PHP, I have received few emails asking how to create a simple PHP session based shopping cart for the website. So, keeping that in mind, today we are going to create a shopping cart, which is simple and can be integrated easily in any website that runs on PHP. I have created 4 files for our shopping cart:
- Config.php (MySql credentials)
- Index.php (list of product information from database)
- Cart_update.php (Updates cart items and redirects back to products list page)
- View_cart.php (Product summery view before the payment)
Products List
All our products information should be stored in MySql table, for that we can create a table named «products» using MySql statement below, you can insert the products details manually using PhpMyAdmin, OR use MySql file in downloadable zip, which you can import in PhpMyAdmin.
CREATE TABLE IF NOT EXISTS `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `product_code` varchar(60) NOT NULL, `product_name` varchar(60) NOT NULL, `product_desc` tinytext NOT NULL, `product_img_name` varchar(60) NOT NULL, `price` decimal(10,2) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `product_code` (`product_code`) ) AUTO_INCREMENT=1 ;
Once you have database table, you can create a list of products, similar to picture below:
Configuration
Purpose of the config file is to store various information we need for our script. Here we are just going to enter MySql authentication details to access database table. Just enter the MySql details in the configuration file.
12, 'Service Tax' => 5 ); //connect to MySql $mysqli = new mysqli($db_host, $db_username, $db_password,$db_name); if ($mysqli->connect_error) < die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); > ?>
Product List (Index.php)
This will be the page where you want to display the list the products you want to sell. If you have lots of products, it is better to group them in pages using some sort of pagination. And on the right side of the page will be our shopping-cart box, which will keep track of items user going to purchase later.Since we are working with sessions, we must activate PHP session in our script by including session_start() on top of the code, then we can start writing other codes or include file:
Listing Products from Database
We will basically fetch the records from database and display them on the page. We will also create a HTML form with Add to Cart button. Important part here is the HTML form, notice the hidden input values? Each item contains a form with these hidden values, product code and the return URL, which we will send to cart_update.php using POST method.
Shopping Cart Box
On the right side of the page we will display small shopping cart box to keep track of user items. The main task of the shopping-cart is to look for session variable called $_SESSION[«cart_products»], which holds the collection of user items in an array, and then retrieve and display its content in the box.
0) < echo 'Your Shopping Cart'; echo ''; echo ''; > ?>
Updating Cart
The role of the Cart_update.php is to add and remove items in the shopping cart. When user clicks «Add to Cart» button, the form sends some hidden values such as product code and quantity to Cart_update.php using POST method, which we will use to retrieve product info from the database verifying the existence of the product, and then we create or update $_SESSION[«cart_products»] with new array variables. Removing item works similar way, please go though comment lines below, most of the code is self explanatory.
0) < foreach($_POST as $key =>$value) < //add all post vars to new_product array $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); >//remove unecessary vars unset($new_product['type']); unset($new_product['return_url']); //we need to get product name and price from database. $statement = $mysqli->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1"); $statement->bind_param('s', $new_product['product_code']); $statement->execute(); $statement->bind_result($product_name, $price); while($statement->fetch()) < //fetch product name, price from db and add to new_product array $new_product["product_name"] = $product_name; $new_product["product_price"] = $price; if(isset($_SESSION["cart_products"]))< //if session var already exist if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array < unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item >> $_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item > > //update or remove items if(isset($_POST["product_qty"]) || isset($_POST["remove_code"])) < //update item quantity in product session if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"]))< foreach($_POST["product_qty"] as $key =>$value) < if(is_numeric($value))< $_SESSION["cart_products"][$key]["product_qty"] = $value; >> > //remove an item from product session if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])) < foreach($_POST["remove_code"] as $key)< unset($_SESSION["cart_products"][$key]); >> > //back to return url $return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url header('Location:'.$return_url);
View Item Summary
Now we have everything ready, its time for final page where user can view their products and proceed to payment. It’s good idea to add taxes, shipping and transaction fees along with total amount in this page for the users to see. You can generate any type of data here for the Payment gateway, most Payment gateway prefer HTML form, so I have create some hidden input fields, you can modify them to suit your needs.
Add a shopping cart to ecommerce website in php
Add a shopping cart to ecommerce website in php with all functions like add and remove items from cart along with check out at once. It is an important feature of all ecommerce webiste. It allows the user to add as many products into his/her shopping cart and later check out with all the items at a time. The user can view, delete or add the items to his cart any time. This makes shopping easy and user friendly.
I have also written a blog to build a shopping cart using ajax and jquery in php.
Let’s see how to add an shopping cart to ecommerce websites in php.
We will follow these basic steps to complete this project:
- Create a cart table in the database.
- Design the index.php page in php
- Design product-details page with add to cart button for every product
- Add the item to the shopping cart in php
- View cart in php
- Delete the item from the shopping cart in php
Create a cart table in the database.
The cart table will have four fields pid , name , price , image . pid is the primary key.
CREATE TABLE cart (pid INT NOT NULL, name TEXT NOT NULL, price INT NOT NULL, image TEXT NOT NULL, email TEXT NOT NULL );
The index page displays all the products from the database. Clicking on the product takes the user to product details page where user can add the product to the cart.
$query1 = "SELECT * FROM products"; $result1 = mysqli_query($db, $query1); if ($result1 == FALSE) < die(mysqli_error()); exit(); >?> .closebtn:hover < color: black; >.width < width: 600px; >@media(max-width: 600px) < .width< width: 350px; >> .width < width: 600px; >@media(max-width: 600px) < .width< width: 350px; >> .wid < width: 400px; >.error < color: red; font-size: large; display: none; >.success < color: green; font-size: large; display: none; >img?>?>" >Product id. Price: Rs.
Important Link:
Design product-details.php page
It contains the product name, image, price and an Add to cart button. Clicking on the add to cart button calls a javascript function.
The javascript function receive all the product values from the form and makes an ajax call to the php server. The server first check for the login status of the user. If the user is not logged in, ask user to login first. The logged in user is able to add the prodcut to the cart. However, if the product is already in the cart, display the message to the user.
> ?> $row = mysqli_fetch_array($result, MYSQLI_ASSOC); $query = "SELECT * FROM product_images WHERE pid='$pid'"; $result1 = mysqli_query($db, $query); if ($result1 == FALSE) < die(mysqli_error()); exit(); >$result1 = mysqli_query($db, $query); $row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC); ?> .width < width: 600px; >@media(max-width: 600px) < .width< width: 350px; >> .width < width: 600px; >@media(max-width: 600px) < .width< width: 350px; >> .wid < width: 400px; >.error < color: red; font-size: large; display: none; cursor: pointer; position: fixed; width: 100%; height: 5%; top: 1; left: 0; right: 0; bottom: 10; background-color: #eee; z-index: 2; opacity: 0.7; >.success < color: green; font-size: large; display: none; cursor: pointer; width: 100%; height: 5%; top: 1; left: 0; right: 0; bottom: 10; background-color: #eee; z-index: 2; opacity: 0.7; >.imageProduct id. Price: Rs.
addtocart.php: Add the item to the shopping cart.
It receives all the product infromation from the front end and add it to the cart table in the database. If the product is already in the cart, display the suitable message to the user.
processMobileVerification(); > function processMobileVerification() < if(!isset($_SESSION['email']))< echo 4; >else < $pid = $_POST['pid']; $name = $_POST['pname']; $price = $_POST['price']; $image = $_POST['image']; $email = $_POST['email']; $query1 = "SELECT * FROM cart WHERE pid= '$pid' && email='$email' "; $result1 = mysqli_query($db,$query1); $row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC); if(!$row1['pid'])< $query= "INSERT INTO cart (pid,name,price,image,email) VALUES('$pid','$name','$price','$image','$email')"; $result = mysqli_query($db,$query); if(!$result)< die(mysqli_error()); echo 3; exit(); >else echo 1; > else echo 2; > > > $controller = new Controller(); ?>home.php: View cart/ Delete item from the cart
The home page displays all the items in the cart with all the related details. It also contains the delete option for every item in the cart. The user can delete the items in the cart any time and continue to shopping or proceed to final checkout.
$email = $_SESSION['email']; include('db-connect.php'); ?> .image < margin: auto; border-radius: 3px; border: 3px solid grey; height: 90px; width: 180px; >.width < width: 600px; >@media(max-width: 600px) < .width< width: 350px; >> .error < color: red; font-size: large; >#message3Hello
" width="150px" height="140px" >
?>Cart
Sl No. Name Product id INR Price Picture Delete ?> Rs. ₹ Total items: Total price : Published on July 16, 2021