How To Create Cart In Php
- Home →
- PHP →
- 7 Steps to Create Simple Shopping Cart Application in PHP & MySQL
0
7 Steps to Create Simple Shopping Cart Application in PHP & MySQL
This is a simple php shopping cart application in PHP & MySQL to display products, add to cart functionality in php and checkout features and also removing products from cart. This shopping cart application is built with simple php & mysql code.
Building E-Commerce Shopping Cart Website in PHP & MySQL
On this page you will find 2 scripts one is simply basic Shopping Cart System and the other one advanced and more complex System.
If you want to build advanced E-Commerce System, Scroll down.
[thrive_leads id='7349′]
Below is the screenshot of all the files that I'm going to create.
1. Creating Template Files
First of all, I'm going to create reusable template files. Create three files with the name of header.php, nav.php, footer.php
header.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <html> <head> <title> Simple Ecommerce Project in PHP & MySQL </title> <!-- Latest compiled and minified CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > <!-- Optional theme --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" > <!-- JQuery --> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" > </script> <!-- Latest compiled and minified JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > </script> </head> <body> <div class = "container" > <div class = "row" > <div class = "col-md-5" > <a class = "img-responsive logo" href = "index.php" > <img src = "logo.png" /> </a> </div> </div> </div> |
nav.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <nav class = "navbar navbar-default" > <div class = "container" > <div class = "navbar-header" > <button type = "button" class = "navbar-toggle collapsed" data-toggle = "collapse" data-target = "#bs-example-navbar-collapse-1" aria-expanded = "false" > <span class = "sr-only" > Toggle navigation </span> <span class = "icon-bar" > </span> <span class = "icon-bar" > </span> <span class = "icon-bar" > </span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class = "collapse navbar-collapse" id = "bs-example-navbar-collapse-1" > <ul class = "nav navbar-nav" > <li> <a href = "index.php" > Shop Home <span class = "sr-only" > (current) </span> </a> </li> <li> <a href = "cart.php" > Cart </a> </li> </ul> <ul class = "nav navbar-nav navbar-right" > <li> <a href = "cart.php" > 2 Items in Cart </a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> |
footer.php
After that create index.php file to list all the products
index.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php session_start ( ) ; require_once ( 'inc/connect.php' ) ; include ( 'templates/header.php' ) ; include ( 'templates/nav.php' ) ; ?> <div class = "container" > <div class = "row" > <div class = "col-sm-6 col-md-3" > <div class = "thumbnail" > <img src = "image.png" alt = "image title" > <div class = "caption" > <h3> Product Name </h3> <p> Product Description </p> <p> $100 </p> <p> <a href = "addtocart.php" class = "btn btn-primary" role = "button" > Add to Cart </a> </p> </div> </div> </div> </div> </div> <?php include ( 'templates/footer.php' ) ; ?> |
2. Creating Database Table
Next create database table with the name of products, you can use this below sql. I've already created few products.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `price` varchar(255) NOT NULL, `description` text NOT NULL, `image` varchar(255) NOT NULL, `date_added` date NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET =latin1; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `title`, `price`, `description`, `image`, `date_added`) VALUES (1, 'IPhone', '800', 'IPhone for sale', 'prod-img/iphone.png', '2017-02-01'), (2, 'MacBook Air', '1500', 'MacBook Air for sale', 'prod-img/macbook-air.png', '2017-02-02'), (3, 'MacBook Pro', '1800', 'MacBook Pro For Sale', 'prod-img/macbook-pro.png', '2017-02-03'), (4, 'IPad Air 2', '1200', 'IPad Air 2 For Sale', 'prod-img/ipad-air2.png', '2017-02-04'); -- -- Indexes for dumped tables -- -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT =5; |
3. Connecting to Database Table
Connecting to database using php, create connect.php file and use this code.
| <?php $connection = mysqli_connect ( 'localhost' , 'root' , '' ) ; if ( ! $connection ) { die ( "Database Connection Failed" . mysqli_error ( $connection ) ) ; } $select_db = mysqli_select_db ( $connection , 'shop' ) ; if ( ! $select_db ) { die ( "Database Selection Failed" . mysqli_error ( $connection ) ) ; } |
Then include this connect.php file in our index.php file. If you are using above code, I've already included it.
4. Displaying Products
Next fetch products from database table using SELECT sql, and display all the products in our shopping cart index.php file.
| $sql = "SELECT * FROM products" ; $res = mysqli_query ( $connection , $sql ) ; |
Replace index.php html code with this code.
| <?php while ( $r = mysqli_fetch_assoc ( $res ) ) { ?> < div class = "col-sm-6 col-md-3" > < div class = "thumbnail" > < img src = "<?php echo $r [ 'image' ] ; ?>" alt = "<?php echo $r [ 'title' ] ?>" > < div class = "caption" > < h3 > <?php echo $r [ 'title' ] ?> < / h3 > < p > <?php echo $r [ 'description' ] ?> < / p > < p > < a href = "addtocart.php?id=<?php echo $r [ 'id' ] ; ?>" class = "btn btn-primary" role = "button" > Add to Cart < / a > < / p > < / div > < / div > < / div > <?php } ?> |
5. Add to Cart Functionality
For Cart functionality in our php shopping cart appliation, I'm going to use sessions. I'll add product item id to session.
Create a php file with the name of addtocart.php. If the get superglobal is set then create session with item id, then redirect user with status success. If any case if the session is not set then it will redirect user to status failed.
| <?php session_start ( ) ; if ( isset ( $_GET [ 'id' ] ) & ! empty ( $_GET [ 'id' ] ) ) { $items = $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } else { header ( 'location: index.php?status=failed' ) ; } ?> |
Above code will works if only one product is added to cart. If you want to add multiple products then you have to use this below code.
Here I'm creating comma separated list with all product id's added to cart, If the session is set. Otherwise, previous code will be executed.
| if ( isset ( $_SESSION [ 'cart' ] ) & ! empty ( $_SESSION [ 'cart' ] ) ) { $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; $items . = "," . $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } else { $items = $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } |
If the product is already added to cart, then I'm not going add it again. For that checking cartitems array with in_array function. If the item exists then user will be redirected to status incart. If the item doesn't exist in session, then that id will be added session.
| $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; if ( in_array ( $_GET [ 'id' ] , $cartitems ) ) { header ( 'location: index.php?status=incart' ) ; } else { $items . = "," . $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } |
6. Displaying Cart Items
Create cart.php file, use this below html code.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php session_start ( ) ; require_once ( 'inc/connect.php' ) ; include ( 'templates/header.php' ) ; include ( 'templates/nav.php' ) ; ?> < div class = "container" > < div class = "row" > < table class = "table" > < tr > < th > S . NO < / th > < th > Item Name < / th > < th > Price < / th > < / tr > < tr > < td > Item number < / td > < td > < a href = "delcart.php?remove=" > Remove < / a > Item Name < / td > < td > $ 1000 < / td > < / tr > < tr > < td > < strong > Total Price < / strong > < / td > < td > < strong > $ 1000 < / strong > < / td > < td > < a href = "#" class = "btn btn-info" > Checkout < / a > < / td > < / tr > < / table > < / div > < / div > <?php include ( 'templates/footer.php' ) ; ?> |
Reading sesison, creating an array of id using explode function.
| <?php $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; ?> |
Fetching data from database and displaying it in table row.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $total = '' ; $i = 1 ; foreach ( $cartitems as $key = > $id ) { $sql = "SELECT * FROM products WHERE id = $id" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; ?> < tr > < td > <?php echo $i ; ?> < / td > < td > < a href = "delcart.php?remove=<?php echo $key ; ?>" > Remove < / a > <?php echo $r [ 'title' ] ; ?> < / td > < td > $ <?php echo $r [ 'price' ] ; ?> < / td > < / tr > <?php $total = $total + $r [ 'price' ] ; $i ++ ; } ?> |
Displaying total price of all item prices below table row.
| < tr > < td > < strong > Total Price < / strong > < / td > < td > < strong > $ <?php echo $total ; ?> < / strong > < / td > < td > < a href = "#" class = "btn btn-info" > Checkout < / a > < / td > < / tr > |
7. Deleting Items from cart
Create a file with the name of delcart.php. I've already added remove link in cart.php.
Here I'm reading session, creating an array with all the items. Removing array element with pocket number using unset php function.
| <?php session_start ( ) ; $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; if ( isset ( $_GET [ 'remove' ] ) & ! empty ( $_GET [ 'remove' ] ) ) { $delitem = $_GET [ 'remove' ] ; unset ( $cartitems [ $delitem ] ) ; $itemids = implode ( "," , $cartitems ) ; $_SESSION [ 'cart' ] = $itemids ; } header ( 'location:cart.php' ) ; |
Complete code of Simple Shopping Cart in PHP & MySQL
If you have any problem arranging above pieces of code. You can use this complete code.
[sociallocker]
templates/header.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <html> <head> <title> Simple Ecommerce Project in PHP & MySQL </title> <!-- Latest compiled and minified CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > <!-- Optional theme --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" > <link rel = "stylesheet" href = "../styles.css" > <!-- JQuery --> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" > </script> <!-- Latest compiled and minified JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > </script> </head> <body> <div class = "container" > <div class = "row" > <div class = "col-md-5" > <a class = "img-responsive logo" href = "index.php" > <img src = "http://codingcyber.com/wp-content/uploads/2016/09/CC_Web_Logo.png" /> </a> </div> </div> </div> |
templates/nav.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <nav class = "navbar navbar-default" > <div class = "container" > <div class = "navbar-header" > <button type = "button" class = "navbar-toggle collapsed" data-toggle = "collapse" data-target = "#bs-example-navbar-collapse-1" aria-expanded = "false" > <span class = "sr-only" > Toggle navigation </span> <span class = "icon-bar" > </span> <span class = "icon-bar" > </span> <span class = "icon-bar" > </span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class = "collapse navbar-collapse" id = "bs-example-navbar-collapse-1" > <ul class = "nav navbar-nav" > <li> <a href = "index.php" > Shop Home <span class = "sr-only" > (current) </span> </a> </li> <li> <a href = "cart.php" > Cart </a> </li> </ul> <ul class = "nav navbar-nav navbar-right" > <li> <a href = "cart.php" > <?php $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; echo count ( $cartitems ) ; ?> Items in Cart </a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> |
templates/footer.php
index.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?php session_start ( ) ; require_once ( 'inc/connect.php' ) ; include ( 'templates/header.php' ) ; include ( 'templates/nav.php' ) ; $sql = "SELECT * FROM products" ; $res = mysqli_query ( $connection , $sql ) ; ?> < div class = "container" > <?php if ( isset ( $_GET [ 'status' ] ) & ! empty ( $_GET [ 'status' ] ) ) { if ( $_GET [ 'status' ] == 'success' ) { echo "<div class=\"alert alert-success\" role=\"alert\">Item Successfully Added to Cart</div>" ; } elseif ( $_GET [ 'status' ] == 'incart' ) { echo "<div class=\"alert alert-info\" role=\"alert\">Item is Already Exists in Cart</div>" ; } elseif ( $_GET [ 'status' ] == 'failed' ) { echo "<div class=\"alert alert-danger\" role=\"alert\">Failed to Add item, try to Add Again</div>" ; } } ?> < div class = "row" > <?php while ( $r = mysqli_fetch_assoc ( $res ) ) { ?> < div class = "col-sm-6 col-md-3" > < div class = "thumbnail" > < img src = "<?php echo $r [ 'image' ] ; ?>" alt = "<?php echo $r [ 'title' ] ?>" > < div class = "caption" > < h3 > <?php echo $r [ 'title' ] ?> < / h3 > < p > <?php echo $r [ 'description' ] ?> < / p > < p > < a href = "addtocart.php?id=<?php echo $r [ 'id' ] ; ?>" class = "btn btn-primary" role = "button" > Add to Cart < / a > < / p > < / div > < / div > < / div > <?php } ?> < / div > < / div > <?php include ( 'templates/footer.php' ) ; ?> |
addtocart.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php session_start ( ) ; if ( isset ( $_GET [ 'id' ] ) & ! empty ( $_GET [ 'id' ] ) ) { if ( isset ( $_SESSION [ 'cart' ] ) & ! empty ( $_SESSION [ 'cart' ] ) ) { $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; if ( in_array ( $_GET [ 'id' ] , $cartitems ) ) { header ( 'location: index.php?status=incart' ) ; } else { $items . = "," . $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } } else { $items = $_GET [ 'id' ] ; $_SESSION [ 'cart' ] = $items ; header ( 'location: index.php?status=success' ) ; } } else { header ( 'location: index.php?status=failed' ) ; } ?> |
cart.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <?php session_start ( ) ; require_once ( 'inc/connect.php' ) ; include ( 'templates/header.php' ) ; include ( 'templates/nav.php' ) ; ?> < div class = "container" > <?php $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; ?> < div class = "row" > < table class = "table" > < tr > < th > S . NO < / th > < th > Item Name < / th > < th > Price < / th > < / tr > <?php $total = '' ; $i = 1 ; foreach ( $cartitems as $key = > $id ) { $sql = "SELECT * FROM products WHERE id = $id" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; ?> < tr > < td > <?php echo $i ; ?> < / td > < td > < a href = "delcart.php?remove=<?php echo $key ; ?>" > Remove < / a > <?php echo $r [ 'title' ] ; ?> < / td > < td > $ <?php echo $r [ 'price' ] ; ?> < / td > < / tr > <?php $total = $total + $r [ 'price' ] ; $i ++ ; } ?> < tr > < td > < strong > Total Price < / strong > < / td > < td > < strong > $ <?php echo $total ; ?> < / strong > < / td > < td > < a href = "#" class = "btn btn-info" > Checkout < / a > < / td > < / tr > < / table > < / div > < / div > <?php include ( 'templates/footer.php' ) ; ?> |
delcart.php
| <?php session_start ( ) ; $items = $_SESSION [ 'cart' ] ; $cartitems = explode ( "," , $items ) ; if ( isset ( $_GET [ 'remove' ] ) & ! empty ( $_GET [ 'remove' ] ) ) { $delitem = $_GET [ 'remove' ] ; unset ( $cartitems [ $delitem ] ) ; $itemids = implode ( "," , $cartitems ) ; $_SESSION [ 'cart' ] = $itemids ; } header ( 'location:cart.php' ) ; |
[/sociallocker]
Building E-Commerce Shopping Cart Website in PHP & MySQL
It's more advanced than the above one and it contains lot of features that you can learn to build E-Commerce Shopping Cart in PHP
[thrive_leads id='7349′]
First of all, you need to have basic HTML template for Shopping Cart application. You can use any basic template or use bootstrap. Here I'm using a template if you want to have access to all the source code join my course.
Here I'm going to build a Shopping Cart with these features
Front End
In FrontEnd Displaying Products and on home page displaying products with categories. Next adding products to cart from homepage category page and also adding products to cart in multiple quantities from the single product page.
Next is displaying products added to cart in cart page and also in the drop-down menu with a checkout link.
While user goes to checkout page after adding products to cart. We will check user logged in or not?
If user logged in we will allow him to the checkout page or else he will be prompted to log in or register.
If he is a new user, he should register. If he is an existing user, he can log in with his login credentials.
In checkout page, if the user already has billing details. It will be displayed or else user will be prompted to enter billing details.
After that user can choose the payment method and accept the terms his order will be placed. For now, I'm using only Cash On Delivery method.
If we use payment gateways, the user will be redirected to a payment gateway. If he pays we will store transaction id and other information from payment gateway provider into our database.
A customer can submit reviews to the product, a customer can submit only one review per product.
The customer can cancel his order. Also, a customer can update his or her address from my account page.
A customer can check all the orders on my account page. And also view single orders from single order view page.
Wishlist for the customer to add products to wishlist and remove products from wishlist.
Back End
In Back End Admin Area, Admin User will be able to log in and add, edit & delete products. And also admin user can check the orders. Go through the list of customers and go through all the reviews submitted by customers.
Order Processing from the backend, admin can process the order in 4 different stages one is Order Placed, Order In Progress, Order Dispatched, and Order Delivered.
A lot more features are included.
Create Database & Tables
First of we will start with creating database and tables, we need couple of tables for our features. I'll create basic tables that we need and we will create other tables as we go along.
First I'll list out all the tables that we need in our project
admin table
category table
products table
users table
usersmeta table
orders table
orderitmes table
orderstracking table
wishlist table
reviews table
For now, I'll create first three tables that is admin table and category table and products table. Here is the SQL code for each one of the table.
In Admin table, I'm creating 5 columns with id, first name, last name, email, password.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET =latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; |
In Category table, I'm creating with 2 columns id, name.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | -- -- Table structure for table `category` -- CREATE TABLE `category` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET =latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `category` -- ALTER TABLE `category` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; In products table, I'm creating 6 columns with id, name, category id, product price, product image thumbnail, product description. -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `catid` int(11) NOT NULL, `price` varchar(255) NOT NULL, `thumb` varchar(255) NOT NULL, `description` varchar(255) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET =latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; |
And I'll create other tables as we go along with project.
2. Creating Required Files
First I'll start with creating files in front end
index.php – we need this file for displaying all products and products based on categories
single.php – for displaying single product details
addtocart.php – for adding items to cart
cart.php – for displaying products in cart
delcart.php – for deleting items from cart.
checkout.php – for customer checkout process
login.php – for users to login/register from same page
loginprocess.php – for login functionality of customer
registerprocess.php – for customer registration process.
my-account.php – for displaying all the orders associated with customer
view-order.php – for displaying single order with more details
cancel-order.php – for cancelling the order
edit-order.php –
addtowishlist.php – for adding items to wishlist
wishlist.php – for displaying products in wishlist
delwishlist.php – for deleting products from wishlist
logout.php –
And also we need inc directory for template files that is header, footer and navigation files
Create a directory with the name of inc and create these files
header.php – used for header code in html and it is reusalbe accross all the files
footer.php – used for closing of html file and it is reusable accross all the files
nav.php – used for navigational menu and it is reused in all the files
And also we need one more directory that is config, in this directory I'll store all the configuration files. For now I'll create database connection file.
connect.php – We will use this file for connecting to database and selecting database.
Then I'll move on to creating necessary files in Admin Area
In Admin area, first of all I'll create directory our reusable template files.
header.php – used for header code in html and it is reusalbe accross all the files in admin area
footer.php – used for closing of html file and it is reusable accross all the files in admin area
nav.php – used for navigational menu and it is reused in all the files in admin area
login.php –
index.php –
caetgories.php –
addcategory.php –
delcategory.php –
editcategory.php –
products.php –
addproduct.php
editproduct.php –
delproduct.php –
delprodimg.php –
orders.php –
order-process.php –
customers.php –
reviews.php –
logout.php –
Admin Login
Before working on login functionality we need database connect for that I'll create
| $connection = mysqli_connect ( 'localhost' , 'root' , '' , 'ecomphp' ) ; if ( ! $connection ) { echo "Error: Unable to connect to MySQL." . PHP_EOL ; echo "Debugging errno: " . mysqli_connect_errno ( ) . PHP_EOL ; echo "Debugging error: " . mysqli_connect_error ( ) . PHP_EOL ; exit ; } |
| session_start ( ) ; require_once '../config/connect.php' ; if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $email = mysqli_real_escape_string ( $connection , $_POST [ 'email' ] ) ; $password = md5 ( $_POST [ 'password' ] ) ; $sql = "SELECT * FROM admin WHERE email='$email' AND password='$password'" ; $result = mysqli_query ( $connection , $sql ) or die ( mysqli_error ( $connection ) ) ; $count = mysqli_num_rows ( $result ) ; if ( $count == 1 ) { //echo "User exits, create session"; $_SESSION [ 'email' ] = $email ; header ( "location: index.php" ) ; } else { $fmsg = "Invalid Login Credentials" ; } } |
Login Checking on index.php and on all admin pages
| session_start ( ) ; require_once '../config/connect.php' ; if ( ! isset ( $_SESSION [ 'email' ] ) & empty ( $_SESSION [ 'email' ] ) ) { header ( 'location: login.php' ) ; } |
Category CRUD in Admin Area
addcategory.php
| if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $name = mysqli_real_escape_string ( $connection , $_POST [ 'categoryname' ] ) ; $sql = "INSERT INTO category (name) VALUES ('$name')" ; $res = mysqli_query ( $connection , $sql ) ; if ( $res ) { $smsg = "Category Added" ; } else { $fmsg = "Failed Add Category" ; } } |
categories.php
| <?php $sql = "SELECT * FROM category" ; $res = mysqli_query ( $connection , $sql ) ; while ( $r = mysqli_fetch_assoc ( $res ) ) { ?> < tr > < th scope = "row" > <?php echo $r [ 'id' ] ; ?> < / th > < td > <?php echo $r [ 'name' ] ; ?> < / td > < td > < a href = "editcategory.php?id=<?php echo $r [ 'id' ] ; ?>" > Edit < / a > | < a href = "delcategory.php?id=<?php echo $r [ 'id' ] ; ?>" > Delete < / a > < / td > < / tr > <?php } ?> |
editcategory.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | if ( isset ( $_GET ) & ! empty ( $_GET ) ) { $id = $_GET [ 'id' ] ; } else { header ( 'location: categories.php' ) ; } if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $id = mysqli_real_escape_string ( $connection , $_POST [ 'id' ] ) ; $name = mysqli_real_escape_string ( $connection , $_POST [ 'categoryname' ] ) ; $sql = "UPDATE category SET name = '$name' WHERE id=$id" ; $res = mysqli_query ( $connection , $sql ) ; if ( $res ) { $smsg = "Category Updated" ; } else { $fmsg = "Failed Update Category" ; } } |
delcategory.php
| if ( isset ( $_GET ) & ! empty ( $_GET ) ) { $id = $_GET [ 'id' ] ; $sql = "DELETE FROM category WHERE id='$id'" ; if ( mysqli_query ( $connection , $sql ) ) { header ( 'location:categories.php' ) ; } } else { header ( 'location: categories.php' ) ; } |
Products CRUD in Admin Area
addproduct.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $prodname = mysqli_real_escape_string ( $connection , $_POST [ 'productname' ] ) ; $description = mysqli_real_escape_string ( $connection , $_POST [ 'productdescription' ] ) ; $category = mysqli_real_escape_string ( $connection , $_POST [ 'productcategory' ] ) ; $price = mysqli_real_escape_string ( $connection , $_POST [ 'productprice' ] ) ; if ( isset ( $_FILES ) & ! empty ( $_FILES ) ) { $name = $_FILES [ 'productimage' ] [ 'name' ] ; $size = $_FILES [ 'productimage' ] [ 'size' ] ; $type = $_FILES [ 'productimage' ] [ 'type' ] ; $tmp_name = $_FILES [ 'productimage' ] [ 'tmp_name' ] ; $max_size = 10000000 ; $extension = substr ( $name , strpos ( $name , '.' ) + 1 ) ; if ( isset ( $name ) && ! empty ( $name ) ) { if ( ( $extension == "jpg" || $extension == "jpeg" ) && $type == "image/jpeg" && $size <= $max_size ) { $location = "uploads/" ; if ( move_uploaded_file ( $tmp_name , $location . $name ) ) { //$smsg = "Uploaded Successfully"; $sql = "INSERT INTO products (name, description, catid, price, thumb) VALUES ('$prodname', '$description', '$category', '$price', '$location$name')" ; $res = mysqli_query ( $connection , $sql ) ; if ( $res ) { //echo "Product Created"; header ( 'location: products.php' ) ; } else { $fmsg = "Failed to Create Product" ; } } else { $fmsg = "Failed to Upload File" ; } } else { $fmsg = "Only JPG files are allowed and should be less that 1MB" ; } } else { $fmsg = "Please Select a File" ; } } else { $sql = "INSERT INTO products (name, description, catid, price) VALUES ('$prodname', '$description', '$category', '$price')" ; $res = mysqli_query ( $connection , $sql ) ; if ( $res ) { header ( 'location: products.php' ) ; } else { $fmsg = "Failed to Create Product" ; } } } |
editproduct.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | if ( isset ( $_GET ) & ! empty ( $_GET ) ) { $id = $_GET [ 'id' ] ; } else { header ( 'location: products.php' ) ; } if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $prodname = mysqli_real_escape_string ( $connection , $_POST [ 'productname' ] ) ; $description = mysqli_real_escape_string ( $connection , $_POST [ 'productdescription' ] ) ; $category = mysqli_real_escape_string ( $connection , $_POST [ 'productcategory' ] ) ; $price = mysqli_real_escape_string ( $connection , $_POST [ 'productprice' ] ) ; if ( isset ( $_FILES ) & ! empty ( $_FILES ) ) { $name = $_FILES [ 'productimage' ] [ 'name' ] ; $size = $_FILES [ 'productimage' ] [ 'size' ] ; $type = $_FILES [ 'productimage' ] [ 'type' ] ; $tmp_name = $_FILES [ 'productimage' ] [ 'tmp_name' ] ; $max_size = 10000000 ; $extension = substr ( $name , strpos ( $name , '.' ) + 1 ) ; if ( isset ( $name ) && ! empty ( $name ) ) { if ( ( $extension == "jpg" || $extension == "jpeg" ) && $type == "image/jpeg" && $size <= $max_size ) { $location = "uploads/" ; $filepath = $location . $name ; if ( move_uploaded_file ( $tmp_name , $filepath ) ) { $smsg = "Uploaded Successfully" ; } else { $fmsg = "Failed to Upload File" ; } } else { $fmsg = "Only JPG files are allowed and should be less that 1MB" ; } } else { $fmsg = "Please Select a File" ; } } else { $filepath = $_POST [ 'filepath' ] ; } $sql = "UPDATE products SET name='$prodname', description='$description', catid='$category', price='$price', thumb='$filepath' WHERE id = $id" ; $res = mysqli_query ( $connection , $sql ) ; if ( $res ) { $smsg = "Product Updated" ; } else { $fmsg = "Failed to Update Product" ; } } |
Form code in editproduct.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?php $sql = "SELECT * FROM products WHERE id=$id" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; ?> < form method = "post" enctype = "multipart/form-data" > < div class = "form-group" > < input type = "hidden" name = "filepath" value = "<?php echo $r [ 'thumb' ] ; ?>" > < label for = "Productname" > Product Name < / label > < input type = "text" class = "form-control" name = "productname" id = "Productname" placeholder = "Product Name" value = "<?php echo $r [ 'name' ] ; ?>" > < / div > < div class = "form-group" > < label for = "productdescription" > Product Description < / label > < textarea class = "form-control" name = "productdescription" rows = "3" > <?php echo $r [ 'description' ] ; ?> < / textarea > < / div > < div class = "form-group" > < label for = "productcategory" > Product Category < / label > < select class = "form-control" id = "productcategory" name = "productcategory" > <?php $catsql = "SELECT * FROM category" ; $catres = mysqli_query ( $connection , $catsql ) ; while ( $catr = mysqli_fetch_assoc ( $catres ) ) { ?> < option value = "<?php echo $catr [ 'id' ] ; ?>" <?php if ( $catr [ 'id' ] == $r [ 'catid' ] ) { echo "selected" ; } ?> > <?php echo $catr [ 'name' ] ; ?> < / option > <?php } ?> < / select > < / div > < div class = "form-group" > < label for = "productprice" > Product Price < / label > < input type = "text" class = "form-control" name = "productprice" id = "productprice" placeholder = "Product Price" value = "<?php echo $r [ 'price' ] ; ?>" > < / div > < div class = "form-group" > < label for = "productimage" > Product Image < / label > <?php if ( isset ( $r [ 'thumb' ] ) & ! empty ( $r [ 'thumb' ] ) ) { ?> < br > < img src = "<?php echo $r [ 'thumb' ] ?>" widht = "100px" height = "100px" > < a href = "delprodimg.php?id=<?php echo $r [ 'id' ] ; ?>" > Delete Image < / a > <?php } else { ?> < input type = "file" name = "productimage" id = "productimage" > < p class = "help-block" > Only jpg / png are allowed . < / p > <?php } ?> < / div > < button type = "submit" class = "btn btn-default" > Submit < / button > < / form > |
delproduct.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | if ( isset ( $_GET [ 'id' ] ) & ! empty ( $_GET [ 'id' ] ) ) { $id = $_GET [ 'id' ] ; $sql = "SELECT thumb FROM products WHERE id=$id" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; if ( ! empty ( $r [ 'thumb' ] ) ) { if ( unlink ( $r [ 'thumb' ] ) ) { $delsql = "DELETE FROM products WHERE id=$id" ; if ( mysqli_query ( $connection , $delsql ) ) { header ( "location:products.php" ) ; } } } else { $delsql = "DELETE FROM products WHERE id=$id" ; if ( mysqli_query ( $connection , $delsql ) ) { header ( "location:products.php" ) ; } } } else { header ( 'location: products.php' ) ; } |
delprodimg.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | if ( isset ( $_GET [ 'id' ] ) & ! empty ( $_GET [ 'id' ] ) ) { $id = $_GET [ 'id' ] ; $sql = "SELECT thumb FROM products WHERE id=$id" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; if ( ! empty ( $r [ 'thumb' ] ) ) { if ( unlink ( $r [ 'thumb' ] ) ) { $delsql = "UPDATE products SET thumb='' WHERE id=$id" ; if ( mysqli_query ( $connection , $delsql ) ) { header ( "location:editproduct.php?id={$id}" ) ; } } else { $delsql = "UPDATE products SET thumb='' WHERE id=$id" ; if ( mysqli_query ( $connection , $delsql ) ) { header ( "location:editproduct.php?id={$id}" ) ; } } } else { $delsql = "UPDATE products SET thumb='' WHERE id=$id" ; if ( mysqli_query ( $connection , $delsql ) ) { header ( "location:editproduct.php?id={$id}" ) ; } } } else { header ( "location:editproduct.php?id={$id}" ) ; } |
products.php
| <?php $sql = "SELECT * FROM products" ; $res = mysqli_query ( $connection , $sql ) ; while ( $r = mysqli_fetch_assoc ( $res ) ) { ?> < tr > < th scope = "row" > <?php echo $r [ 'id' ] ; ?> < / th > < td > <?php echo $r [ 'name' ] ; ?> < / td > < td > <?php echo $r [ 'catid' ] ; ?> < / td > < td > <?php if ( $r [ 'thumb' ] ) { echo "Yes" ; } else { echo "No" ; } ?> < / td > < td > < a href = "editproduct.php?id=<?php echo $r [ 'id' ] ; ?>" > Edit < / a > | < a href = "delproduct.php?id=<?php echo $r [ 'id' ] ; ?>" > Delete < / a > < / td > < / tr > <?php } ?> |
Displaying Product in Front End
index.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | < div id = "shop-mason" class = "shop-mason-4col" > <?php $sql = "SELECT * FROM products" ; if ( isset ( $_GET [ 'id' ] ) & ! empty ( $_GET [ 'id' ] ) ) { $id = $_GET [ 'id' ] ; $sql . = " WHERE catid=$id" ; } $res = mysqli_query ( $connection , $sql ) ; while ( $r = mysqli_fetch_assoc ( $res ) ) { ?> < div class = "sm-item isotope-item" > < div class = "product" > < div class = "product-thumb" > < img src = "admin/<?php echo $r [ 'thumb' ] ; ?>" class = "img-responsive" width = "250px" alt = "" > < div class = "product-overlay" > < span > < a href = "single.php?id=<?php echo $r [ 'id' ] ; ?>" class = "fa fa-link" > < / a > < a href = "addtocart.php?id=<?php echo $r [ 'id' ] ; ?>" class = "fa fa-shopping-cart" > < / a > < / span > < / div > < / div > < div class = "rating" > < span class = "fa fa-star act" > < / span > < span class = "fa fa-star act" > < / span > < span class = "fa fa-star act" > < / span > < span class = "fa fa-star act" > < / span > < span class = "fa fa-star act" > < / span > < / div > < h2 class = "product-title" > < a href = "single.php?id=<?php echo $r [ 'id' ] ; ?>" > <?php echo $r [ 'name' ] ; ?> < / a > < / h2 > < div class = "product-price" > INR <?php echo $r [ 'price' ] ; ?> . 00 / - < span > < / span > < / div > < / div > < / div > <?php } ?> < / div > |
Add to Cart Functionality
addtocart.php
| session_start ( ) ; if ( isset ( $_GET ) & ! empty ( $_GET ) ) { $id = $_GET [ 'id' ] ; if ( isset ( $_GET [ 'quant' ] ) & ! empty ( $_GET [ 'quant' ] ) ) { $quant = $_GET [ 'quant' ] ; } else { $quant = 1 ; } $_SESSION [ 'cart' ] [ $id ] = array ( "quantity" = > $quant ) ; header ( 'location: cart.php' ) ; } else { header ( 'location: cart.php' ) ; } |
Customer Login & Registration
loginprocess.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | session_start ( ) ; require_once 'config/connect.php' ; if ( isset ( $_POST ) & ! empty ( $_POST ) ) { $email = filter_var ( $_POST [ 'email' ] , FILTER_SANITIZE_EMAIL ) ; $password = $_POST [ 'password' ] ; $sql = "SELECT * FROM users WHERE email='$email'" ; $result = mysqli_query ( $connection , $sql ) or die ( mysqli_error ( $connection ) ) ; $count = mysqli_num_rows ( $result ) ; $r = mysqli_fetch_assoc ( $result ) ; if ( $count == 1 ) { if ( password_verify ( $password , $r [ 'password' ] ) ) { //echo "User exits, create session"; $_SESSION [ 'customer' ] = $email ; $_SESSION [ 'customerid' ] = $r [ 'id' ] ; header ( "location: checkout.php" ) ; } else { //$fmsg = "Invalid Login Credentials"; header ( "location: login.php?message=1" ) ; } } else { header ( "location: login.php?message=1" ) ; } } |
registerprocess.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | session_start ( ) ; require_once 'config/connect.php' ; if ( isset ( $_POST ) & ! empty ( $_POST ) ) { //$email = mysqli_real_escape_string($connection, $_POST['email']); $email = filter_var ( $_POST [ 'email' ] , FILTER_SANITIZE_EMAIL ) ; $password = password_hash ( $_POST [ 'password' ] , PASSWORD_DEFAULT ) ; //$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'"; echo $sql = "INSERT INTO users (email, password) VALUES ('$email', '$password')" ; $result = mysqli_query ( $connection , $sql ) or die ( mysqli_error ( $connection ) ) ; if ( $result ) { //echo "User exits, create session"; $_SESSION [ 'customer' ] = $email ; $_SESSION [ 'customerid' ] = mysqli_insert_id ( $connection ) ; header ( "location: checkout.php" ) ; } else { //$fmsg = "Invalid Login Credentials"; header ( "location: login.php?message=2" ) ; } } |
logout.php
| session_start ( ) ; unset ( $_SESSION [ 'cart' ] ) ; unset ( $_SESSION [ 'customer' ] ) ; header ( 'location: login.php' ) ; |
Storing Customer Billing Details in Checkout Page
checkout.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | if ( isset ( $_POST ) & ! empty ( $_POST ) ) { if ( $_POST [ 'agree' ] == true ) { $country = filter_var ( $_POST [ 'country' ] , FILTER_SANITIZE_STRING ) ; $fname = filter_var ( $_POST [ 'fname' ] , FILTER_SANITIZE_STRING ) ; $lname = filter_var ( $_POST [ 'lname' ] , FILTER_SANITIZE_STRING ) ; $company = filter_var ( $_POST [ 'company' ] , FILTER_SANITIZE_STRING ) ; $address1 = filter_var ( $_POST [ 'address1' ] , FILTER_SANITIZE_STRING ) ; $address2 = filter_var ( $_POST [ 'address2' ] , FILTER_SANITIZE_STRING ) ; $city = filter_var ( $_POST [ 'city' ] , FILTER_SANITIZE_STRING ) ; $state = filter_var ( $_POST [ 'state' ] , FILTER_SANITIZE_STRING ) ; $phone = filter_var ( $_POST [ 'phone' ] , FILTER_SANITIZE_NUMBER_INT ) ; $payment = filter_var ( $_POST [ 'payment' ] , FILTER_SANITIZE_STRING ) ; $zip = filter_var ( $_POST [ 'zipcode' ] , FILTER_SANITIZE_NUMBER_INT ) ; $sql = "SELECT * FROM usersmeta WHERE uid=$uid" ; $res = mysqli_query ( $connection , $sql ) ; $r = mysqli_fetch_assoc ( $res ) ; $count = mysqli_num_rows ( $res ) ; if ( $count == 1 ) { //update data in usersmeta table $usql = "UPDATE usersmeta SET country='$country', firstname='$fname', lastname='$lname', address1='$address1', address2='$address2', city='$city', state='$state', zip='$zip', company='$company', mobile='$phone' WHERE uid=$uid" ; $ures = mysqli_query ( $connection , $usql ) or die ( mysqli_error ( $connection ) ) ; if ( $ures ) { } } else { //insert data in usersmeta table $isql = "INSERT INTO usersmeta (country, firstname, lastname, address1, address2, city, state, zip, company, mobile, uid) VALUES ('$country', '$fname', '$lname', '$address1', '$address2', '$city', '$state', '$zip', '$company', '$phone', '$uid')" ; $ires = mysqli_query ( $connection , $isql ) or die ( mysqli_error ( $connection ) ) ; if ( $ires ) { } } } } |
Placing Order by Customer
checkout.php
| $total = 0 ; foreach ( $cart as $key = > $value ) { //echo $key . " : " . $value['quantity'] ."<br>"; $ordsql = "SELECT * FROM products WHERE id=$key" ; $ordres = mysqli_query ( $connection , $ordsql ) ; $ordr = mysqli_fetch_assoc ( $ordres ) ; $total = $total + ( $ordr [ 'price' ] * $value [ 'quantity' ] ) ; |
[thrive_leads id='7349′]
If you have any problem, let me know through the comment form below.
Vivek Vengala
Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.
How To Create Cart In Php
Source: https://codingcyber.org/simple-shopping-cart-application-php-mysql-6394/
Posted by: wilketherechat.blogspot.com

0 Response to "How To Create Cart In Php"
Post a Comment