All shopping php category

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.

    PHP code for shopping cart system using Twitter Bootstrap Templates

    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.

    Источник

    Simple PHP Shopping Cart

    Building a PHP shopping cart eCommerce software is simple and easy. In this tutorial, let’s create a simple PHP shopping cart software with MySQL.

    The intention of this shopping cart software is that it should be simple and as minimal as possible. You can download this free and customize it for your needs within minutes.

    shopping

    PHP Shopping Cart Software Development Overview

    PHP shopping cart example has the following functionality:

    1. Retrieve product information from the database.
    2. Create product gallery for the shopping cart.
    3. Manage cart items using the PHP session.
    4. Handle add, edit, remove and empty cart actions.

    I have retrieved information like name, code, price, and photos from the database. The resultant information is in an array format.

    I have iterated this resultant array to form the product gallery. Every product in the gallery will have an add-to-cart option.

    I have used the PHP shopping cart session to store and manage the items in the cart.

    Once the session expires, the cart items get cleared. This code has an option to clear the entire cart or to remove any particular item from the cart.

    File Structure

    The shopping cart software example has the following file structure. The below list has the file names and their responsibility.

    You can build a gallery-based shopping cart software with these files in few minutes.

    • dbcontroller.php – a generic database layer to help with DAO functions. It also manages the database connection.
    • index.php – to display the product gallery for the shopping cart.
    • style.css – to showcase products for the shopping cart. The styles are minimal and cross-browser compatible.
    • tblproduct.sql – contains SQL script with the product table structure and the data.
    • product-images – a folder that contains the product images. I have used these images to show the product gallery.

    If you are familiar with online shopping, you might have across product galleries. It is an important gateway in a shopping cart application.

    Users will use the product gallery to get a feel of the products available to buy. It is a critical component of every online store.

    You should always provide a catalog of the available products to let them have a glance. It helps to promote your products to impulsive buyers.

    In the following code, I have shown the PHP script to get the product results from the database. The result will be an array and iterated to create a product card in each iteration.

    The DBController.php class will handle the DAO operation and fetch products result.

    runQuery("SELECT * FROM tblproduct ORDER BY id ASC"); if (!empty($product_array)) < foreach($product_array as $key=>$value) < ?> 
    ">
    > ?>

    Adding Products to Shopping Cart

    After creating the product gallery page, we need to work on the PHP code to perform the cart actions. They are add-to-cart, remove a single item from the cart, clear the complete cart and similar.

    In the above code, I have added the HTML option to add the product to the shopping cart from the product gallery. When the user clicks the ‘Add to Cart’ button, the HTML form passes the product id to the backend PHP script.

    In PHP, I receive and process the cart action with a switch control statement. I have created PHP switch cases to handle the add-to-cart, remove-single, empty-cart actions.

    The action is the argument to the switch statement. Then it executes the corresponding action case as requested.

    The “add” case handles the add to cart action. In this case, I have received the product id and the quantity.

    The cart session stores the submitted product. I have updated the quantity of the product if it already exists in the session cart. The PHP session index is the reference to perform this action.

    case "add": if(!empty($_POST["quantity"])) < $productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'"); $itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"])); if(!empty($_SESSION["cart_item"])) < if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) < foreach($_SESSION["cart_item"] as $k =>$v) < if($productByCode[0]["code"] == $k) < if(empty($_SESSION["cart_item"][$k]["quantity"])) < $_SESSION["cart_item"][$k]["quantity"] = 0; >$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; > > > else < $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); >> else < $_SESSION["cart_item"] = $itemArray; >> break; 

    List Cart Items from the PHP Session

    This code shows the HTML to display the shopping cart with action controls. The loop iterates the cart session to list the cart items in a tabular format.

    Each row shows the product image, title, price, item quantity with a remove option. Also, it shows the total item quantity and the total item price by summing up the individual cart items.

     
    Shopping Cart
    Empty Cart ?>
    Name Code Quantity Unit Price Price Remove
    " /> " >Remove Item
    Total:
    else < ?>
    Your Cart is Empty
    ?>

    Removing or Clearing Cart Item

    The loop iterates the cart session array to display the cart items. Each cart item will have a remove link.

    If the shopping cart user clicks the remove link then, I remove the respective cart item from the session.

    I have provided an ‘Empty Cart’ button control above the shopping cart. The users can use it to completely wipe out the cart session and clear the cart.

    I have presented the PHP code below to “remove” and the “empty” cases. They handle the shopping cart to remove/clear actions.

    I have used PHP unset() to clear the cart session to delete the added item from the shopping cart.

    case "remove": if(!empty($_SESSION["cart_item"])) < foreach($_SESSION["cart_item"] as $k =>$v) < if($_GET["code"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); >> break; case "empty": unset($_SESSION["cart_item"]); break; 

    Database Product Table for Shopping Cart

    You should import the following SQL script. It will create the product table and load data into it. In the example, I have used this product data to display products in the gallery.

    -- -- Table structure for table `tblproduct` -- CREATE TABLE `tblproduct` ( `id` int(8) NOT NULL, `name` varchar(255) NOT NULL, `code` varchar(255) NOT NULL, `image` text NOT NULL, `price` double(10,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblproduct` -- INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES (1, 'FinePix Pro2 3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00), (2, 'EXP Portable Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00), (3, 'Luxury Ultra thin Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00), (4, 'XP 1155 Intel Core Laptop', 'LPN45', 'product-images/laptop.jpg', 800.00); -- -- Indexes for table `tblproduct` -- ALTER TABLE `tblproduct` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `product_code` (`code`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tblproduct` -- ALTER TABLE `tblproduct` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; COMMIT; 

    Simple PHP Shopping Cart Output

    The below screenshot shows the product gallery of this simple PHP shopping cart example. The listed cart items above the gallery are from the PHP session.

    php-shopping-cart

Оцените статью