Logo of The ProTec Professional Training Institute
The Protec is registered with STEVTA and Affiliated with TTB Sindh

How to create Add to Cart in your PHP website

Part 1 - PHP (Hypertext Pre Processor) Tutorials


PHP (Hypertext Pre Processor)
PHP Lecture on how to create simple and easy add to cart in your core PHP website, this tutorial/code will help you to convert your website into online shopping store. This tutorial will help you to develop an E-Commerce site.

Tutorial Details


Learn PHP (Hypertext Pre Processor) in easy way with The Protec, these tutorials will help you to understand Php concepts from basic to advance. to learn PHP its better to have knowledge and understanding of HTML, CSS and JS, other then that knowledge of Mysql is also needed to develop effective php applications.
To create add to cart functionality in your PHP website, you will need to execute the following code.

Orders Page

Create an order.php page and copy and paste following code in it

&lt;?php require('head.php'); $status=""; if (isset($_POST['submit'])) { $qry = "INSERT into orders values(null, '".$_POST['custName']."', '".$_POST['custMob']."', '".$_POST['custEmail']."', '".$_POST['custAddress']."', CURRENT_TIMESTAMP);"; $myCon->query($qry); $oId = $myCon->insert_id; foreach($_POST['id'] as $id) { $qry = "insert into orderProducts values(null, '".$oId."','".$id."', '".$_POST['prdPr'.$id]."', '".$_POST['quantity'.$id]."');"; $myCon->query($qry); } echo "<script>alert('Order Added, your order id is ".$oId."');</script>"; unset($_SESSION["shopping_cart"]); echo "<script>window.location.replace('/');</script>"; } ?> <!DOCTYPE html> <html> <head> <title>Order Page &lt;?php echo webTitle?></title> &lt;?php myHead(); ?> </head> <body> &lt;?php myHeader(); ?> <div class="cart"> <form method="post" action=""> <div class="md-form mb-4"> <label data-error="wrong" data-success="right">Your Name</label> <input type="text" value="adfdas" name="custName" class="form-control validate" placeholder="Your Name" required> </div> <div class="md-form mb-4"> <label data-error="wrong" data-success="right">Your Number</label> <input type="tel" value="03002234179" name="custMob" class="form-control validate" placeholder="Your Number Like 03002234179" pattern="[0-9]{11}" required> </div> <div class="md-form mb-4"> <label data-error="wrong" data-success="right">Your email</label> <input type="email" value="abc@gmail.com" name="custEmail" class="form-control validate" placeholder="Your email" required> </div> <div class="md-form mb-4"> <label data-error="wrong" data-success="right">Your Address</label> <input type="text" value="Naval Colony Karachi." name="custAddress" class="form-control validate" placeholder="Your Address" required> </div> &lt;?php if(isset($_SESSION["shopping_cart"])){ $total_price = 0; ?> <table class="table"> <tbody> <tr> <td></td> <td>ITEM NAME</td> <td>RAM</td> <td>ROM</td> <td>QUANTITY</td> <td>UNIT PRICE</td> <td>ITEMS TOTAL</td> </tr> &lt;?php $count=0; foreach ($_SESSION["shopping_cart"] as $product){ ?> <tr> <td> <img src='&lt;?php echo "/images/mobiles/front/".$product['id'].".jpg"; ?>' width="50" height="40" /> </td> <td>&lt;?php echo $product["brandName"].' '.$product["model"]; ?><br /> <input type='hidden' name='rmvid' value="&lt;?php echo $product["id"]; ?>" /> <input type='hidden' name='action' value="remove" /> <input type='button' name="remove" class='remove' value='Remove Item'> </td> <td>&lt;?php echo $product["ram"]/1024; ?> GB(s)</td> <td>&lt;?php echo $product["rom"]; ?> GB(s)</td> <td> <input type='hidden' name='id[]' value="&lt;?php echo $product["id"]; ?>" /> <input type='hidden' name='prdPr&lt;?php echo $product["id"]; ?>' value="&lt;?php echo $product["price"]; ?>" /> <input type='hidden' name='action' value="change" /> <select name='quantity&lt;?php echo $product["id"]; ?>' class='quantity' onchange="updatePrice(this.value, '&lt;?php echo $product["id"]?>')"> <option &lt;?php if($product["quantity"]==1) echo "selected";?> value="1">1</option> <option &lt;?php if($product["quantity"]==2) echo "selected";?> value="2">2</option> <option &lt;?php if($product["quantity"]==3) echo "selected";?> value="3">3</option> <option &lt;?php if($product["quantity"]==4) echo "selected";?> value="4">4</option> <option &lt;?php if($product["quantity"]==5) echo "selected";?> value="5">5</option> </select> </td> <td>PKR <span id="prdPr&lt;?php echo $product["id"]; ?>">&lt;?php echo $product["price"]; ?></span></td> <td>PKR <span id="prdTt&lt;?php echo $product["id"]; ?>">&lt;?php echo $product["price"]*$product["quantity"]; ?></span></td> </tr> &lt;?php $total_price += ($product["price"]*$product["quantity"]); } ?> <tr> <td colspan="5" align="right"> <strong>TOTAL: PKR <span id="total">&lt;?php echo $total_price; ?></span></strong> </td> </tr> </tbody> </table> <div class="modal-footer d-flex justify-content-center"> <input type="submit" class="btn btn-success" name="submit" value="submit"> </div> </form> &lt;?php }else{ echo "<h3>Your cart is empty!</h3>"; } ?> </div> <div style="clear:both;"></div> <div class="message_box" style="margin:10px 0px;"> &lt;?php echo $status; ?> </div> <script> $('table').on('click', 'input[type="button"]', function(e){ $(this).closest('tr').remove() }); function updatePrice(qty, prdPr) { var price = Number(document.getElementById("prdPr"+prdPr).innerHTML); var prTt = document.getElementById("prdTt"+prdPr); document.getElementById('total').innerHTML = Number(document.getElementById('total').innerHTML)-Number(prTt.innerHTML)+(qty*price); prTt.innerHTML = qty*price; } </script> &lt;?php myFooter(); ?> </body> &lt;/html>

Home Page / or page where you want Add to Cart Button

Add following codes to all your pages where you want add to cart functionality

First copy below mentioned code to the top of your website in php tags

&lt;?php session_start(); if(isset($_POST['addCart'])) { $id = $_POST['pId']; $result = $myCon->query( "SELECT * from mobiles inner join brands on mobiles.brandId = brands.brandId WHERE `mobId`='$id'" ); $row = $result->fetch_assoc(); $model = $row['model']; $brandName = $row['brandName']; $ram = $row['ram']; $rom = $row['rom']; $price = $row['price']; $cartArray = array( $id=>array( 'model'=>$model, 'brandName'=>$brandName, 'ram'=>$ram, 'rom'=>$rom, 'id'=>$id, 'price'=>$price, 'quantity'=>1) ); if(empty($_SESSION["shopping_cart"])) { $_SESSION["shopping_cart"] = $cartArray; $status = "Product is added to your cart!"; }else{ $array_keys = array_keys($_SESSION["shopping_cart"]); if(in_array($id,$array_keys)) { $status = " Product is already added to your cart!"; } else { $_SESSION["shopping_cart"] = array_merge( $_SESSION["shopping_cart"], $cartArray ); $status = "Product is added to your cart!"; } } } ?>

Copy this code to print your products, change variable names according to your database columns

<div class="container"> <div class="row"> <div class="col-12"> &lt;?php if(isset($status)) { echo '<div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> '.$status.' </div>'; } ?> </div> &lt;?php $qry ="select * from mobiles inner join brands on mobiles.brandId = brands.brandId;"; $output = $myCon->query($qry); while($row = $output->fetch_assoc()) { echo '<div class="col-sm-6 col-md-4 col-lg-3"><div class="card" style="width:100%"> <img class="card-img-top" src="images/mobiles/front/'.$row['mobId'].'.jpg" alt="'.$row['brandName'].' '.$row['model'].' available at PKR '.$row['price'].' in Pakistan, Mobile Prices by mobileszila.com" width="100%" height="320px;"> <div class="card-body"> <form method="POST"> <input type="text" name="pId" value="'.$row['mobId'].'" hidden> <h4 class="card-title">'.$row['brandName'].' '.$row['model'].'</h4> <p class="card-text">PKR '.$row['price'].'.</p> <a href="#" class="btn btn-primary">Details</a> <button type="submit" name="addCart" class="btn btn-success">Add to Cart</button> </form> </div> </div></div>'; } ?> </div> </div>

Cart Icon

Copy the below code to show Cart Icon, it help to show how much items are in the cart currently.

if(!empty($_SESSION["shopping_cart"])) { $cart_count = count(array_keys($_SESSION["shopping_cart"])); echo '<li class="nav-item"> <a href="pages/order.php"><img src="images/cart-icon.png" style="width:40px"/> Cart<span> '.$cart_count.'</span></a> </li>'; }

ALL ONLINE COURSES


Leave a Message
0