How to Develop eCommerce Software with Discount Coupon

by Vincy. Last modified on September 27th, 2022.

In this internet era I hope most of us are well aware of how the eCommerce software with discount coupon works. There are numerous of eCommerce stores around the world selling voluminous products online.

In a general shopping cart application, the cart page contains various different functionality. For example, the options like add, remove and updating the cart data, applying discount, taxes and more. Previously, we have seen a simple PHP shopping cart example with cart action tools.

eCommerce Software with Discount

In this example, we are going to see how to add an option to apply discount on the cart item total price.

Adding discount option in a shopping cart software is one of the most wanted features. This article would be a simple manual by providing a step by step guidance to implement eCommerce software with discount coupon.

In a previous tutorial, we have seen several examples for creating eCommerce software using PHP.

The cart items are managed in PHP Session and used in the process of cart flow. It can also be preserved in the database to have a persistent cart system for the eCommerce application.

What is inside?

  1. Advantages of using discount code in eCommerce software
  2. About eCommerce software with discount coupon code example
  3. HTML Code to Create Shopping Cart Software Interface with Discount Coupon
  4. Client and server side validation on the Discount Coupon input
  5. Other code area to display gallery and handle cart actions
  6. File structure
  7. Database script
  8. eCommerce Software with discount option Output

Advantages of using discount code in eCommerce software

In general eCommerce applications announces discount offers, gift vouchers as like as physical stores. This kind of pricing offers will work for the online stores compared to other offline businesses. Because the applications might provide an option for internal marketing invite more customers via customers.

The discount option in a eCommerce software will create many advantages for the application. Some of them are stated below.

  • Offering discounts is a powerful feature to enthusiast customers to make decision for shopping with us.
  • Discounts gives the surprise factor and increases sales.
  • It is the promotional factor for the products on which some special discount offer is announced.
  • Discount codes in the form of fractional ratio or fixed amount in e-commerce software encourages customer to make their profitable purchases.
  • Seasonal discount offers will be used to gain customer inflow and sales on the particular festival or season.
  • Discounts is one of the effective way or marketing strategy to popularize our online stores and increase sales.
  • Discount coupons offered to utilize multiple time will encourage the customers and also leads reputation and promotion to the software.

About eCommerce software with discount coupon code example

In this example, we are going to display product gallery with an add to cart option. The products are dynamic that are fetched from the database.

By adding products to the cart it could be seen above the gallery interface. The added cart items are tracked and managed in a PHP session array.

Though we have seen all these functionality like add-to-cart, product gallery,and more in the previous shopping cart examples, I have once again covered those parts of the code for continuity. Added to that, a form interface is added below the cart to get and apply discount on the purchases.

In this form, an input field is used to collect discount coupon from the customers. The discount coupon is stored in the database. If the user enters valid discount coupon then the we are going to see how to implement Apply discount feature in the eCommerce software.

If the discount is applied when there is no items in the cart then the discount code validation will cover up the irrelevant action performed by the user.

HTML Code to Create Shopping Cart Software Interface with Discount Coupon

The user interface of this shopping cart example can be separated into two parts the cart and the product gallery. In the gallery the products are shown with a card-like view.

On each product card it contains an add-to-cart option. Then the added items can be seen in the cart list which is shown above the gallery.

The cart items are shown in a table view and it contains an option to apply discount coupon. By submitting the discount coupon the form will be validated by using JavaScript.

Once the validation is done, then the discount amount will be applied on the shopping cart items total price.

Below code shows the PHP HTML code to display the dynamic products, cart items on the browser.

<form id="applyDiscountForm" method="post"
	action="index.php?action=show_discount"
	onsubmit="return validate();">

	<div id="shopping-cart">
		<div class="txt-heading">eCommerce software with discount
			coupon</div>
		<a id="btnEmpty" href="index.php?action=empty">Empty Cart</a>
<?php
if (isset($_SESSION["cart_item"])) {
	$total_quantity = 0;
	$total_price = 0;
	
	$discount = $discountPrice;
	$total_price_after_discount = 0;
	?>	
			<table class="tbl-cart" cellpadding="10" cellspacing="1">
			<tbody>
				<tr>
					<th style="text-align: left;">Name</th>
					<th style="text-align: left;">Code</th>
					<th style="text-align: right;" width="5%">Quantity</th>
					<th style="text-align: right;" width="10%">Unit
						Price</th>
					<th style="text-align: right;" width="10%">Price</th>
					<th style="text-align: center;" width="5%">Remove</th>
				</tr>	

					<?php
	foreach ($_SESSION["cart_item"] as $item) {
		$item_price = $item["quantity"] * $item["price"];
		?>
						<tr>
					<td><img src="<?php echo $item["image"]; ?>"
						class="cart-item-image" /><?php echo $item["name"]; ?></td>
					<td><?php echo $item["code"]; ?></td>
					<td style="text-align: right;"><?php echo $item["quantity"]; ?></td>
					<td style="text-align: right;"><?php echo "$ " . $item["price"]; ?></td>
					<td style="text-align: right;"><?php echo "$ " . number_format($item_price, 2); ?></td>
					<td style="text-align: center;"><a
						href="index.php?action=remove&code=<?php echo $item["code"]; ?>"
						class="btnRemoveAction"><img
							src="icon-delete.png" alt="Remove Item" /></a></td>
				</tr>
						<?php
		$total_quantity += $item["quantity"];
		$total_price += ($item["price"] * $item["quantity"]);
		if ($total_price > $discount) {
			$total_price_after_discount = $total_price - $discount;
		}
	}
	?>
					<tr>
					<td colspan="2" align="right">Total:<input
						type="hidden" name="totalPrice"
						id="totalPrice"
						value="<?php echo $total_price; ?>"></td>
					<td align="right"><?php echo $total_quantity; ?></td>
					<td align="right" colspan="2"><strong><?php echo "$ " . number_format($total_price, 2); ?></strong></td>
					<td></td>
				</tr>
				<tr>
					<td colspan="3" align="right">Discount:<input
						type="hidden" name="discountPrice"
						id="discountPrice"
						value="<?php echo $discount; ?>"></td>
					<td align="right" colspan="2"><strong><?php echo "$ " . number_format($discount, 2); ?></strong></td>
					<td></td>
				</tr>
				<tr>
					<td colspan="3" align="right">Total after
						Discount:</td>
					<td align="right" colspan="2"><strong><?php echo "$ " . number_format($total_price_after_discount, 2); ?></strong></td>
					<td></td>
				</tr>
			</tbody>
		</table>		
		<?php
} else {
	?>
			<div class="no-records">Your Cart is Empty</div>
		<?php
}
?>
	</div>
</form>

The following HTML code is to show a discount option below the cart table view.

<div id="discount-grid">
		<div class="discount-section">
			<div class="discount-action">
				<span id="error-msg-span" class="error-message">
				<?php
				if (! empty($message)) {
					echo $message;
				}
				?>
				</span> <span></span><input type="text"
					class="discount-code" id="discountCode"
					name="discountCode" size="15"
					placeholder="Enter Coupon Code" /><input
					id="btnDiscountAction" type="submit"
					value="Apply Discount" class="btnDiscountAction" />
			</div>
		</div>
	</div>

Client and server side validation on the discount coupon input

By applying the discount coupon via the HTML form, the code must be validated before applying the total on shopping cart items.

In this example, I have added a simple JavaScript validation to apply the not-empty check on the discount input data. Once the validation is succeeded then the form will be submitted to the PHP.

<script>
function validate() {
    var valid= true;
     if($("#discountCode").val() === "") {
        valid = false;
     }

     if(valid == false) {
         $('#error-msg-span').text("Discount Coupon Required");
     }
     return valid;
}
</script>

When the discount coupon is submitted to the eCommerce software backend, the server-side validation will take place. The applied code will be verified with the shopping cart database. If no match found then the “Invalid Code” error will be displayed to the user.

As per this example, the discount amount must me less than the cart items total price. Otherwise, the error message will be shown to the user.

case "show_discount":
	if (! empty($_SESSION["cart_item"])) {
		if (! empty($_POST["discountCode"])) {
			$priceByCode = $db_handle->runQuery("SELECT price FROM tbl_discount_coupon WHERE discount_code='" . $_POST["discountCode"] . "'");
			
			if (! empty($priceByCode)) {
				foreach ($priceByCode as $key => $value) {
					$discountPrice = $priceByCode[$key]["price"];
				}
				if (! empty($discountPrice) && $discountPrice > $_POST["totalPrice"]) {
					$message = "Invalid Discount Coupon";
				}
			} else {
				$message = "Invalid Discount Coupon";
			}
		}
	} else {
		$message = "Not applicable. The cart is empty";
	}
	break;

In this section, we are going to see the code to php shopping cart software product gallery and handle cart action. Since this part of an eCommerce software example is discussed enough in previous articles, I didn’t describe this code here in this article.

Displaying Product gallery

<div id="product-grid">
	<div class="txt-heading">Products</div>
		<?php
		$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
		if (! empty($product_array)) {
			foreach ($product_array as $key => $value) {
				?>
				<div class="product-item">
		<form method="post"
			action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
			<div class="product-image">
				<img
					src="<?php echo $product_array[$key]["image"]; ?>">
			</div>
			<div class="product-tile-footer">
				<div class="product-title"><?php echo $product_array[$key]["name"]; ?></div>
				<div class="product-price"><?php echo "$" . $product_array[$key]["price"]; ?></div>
				<div class="cart-action">
					<input type="text" class="product-quantity"
						name="quantity" value="1" size="2" /><input
						type="submit" value="Add to Cart"
						class="btnAddAction" />
				</div>
			</div>
		</form>
	</div>
	<?php
		}
	}
	?>
</div>

PHP code to handle cart actions

<?php
session_start();
require_once ("dbcontroller.php");
$db_handle = new DBController();

if (! empty($_GET["action"])) {
    switch ($_GET["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;
        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 "show_discount":
            if (! empty($_SESSION["cart_item"])) {
                if (! empty($_POST["discountCode"])) {
                    $priceByCode = $db_handle->runQuery("SELECT price FROM tbl_discount_coupon WHERE discount_code='" . $_POST["discountCode"] . "'");
                    
                    if (! empty($priceByCode)) {
                        foreach ($priceByCode as $key => $value) {
                            $discountPrice = $priceByCode[$key]["price"];
                        }
                        if (! empty($discountPrice) && $discountPrice > $_POST["totalPrice"]) {
                            $message = "Invalid Discount Coupon";
                        }
                    } else {
                        $message = "Invalid Discount Coupon";
                    }
                }
            } else {
                $message = "Not applicable. The cart is empty";
            }
            break;
        case "empty":
            unset($_SESSION["cart_item"]);
            break;
    }
}
?>

File structure

Below file structure shows the files used in this example to create the eCommerce software with discount option. Also, it shows the simplicity of this example with minimum number of files.

eCommerce with Discount Example File Structure

Database script

The following database script will be used while setting up this example in your PHP environment. Open your database client and import this script to display shopping cart product gallery and validate discount with the database.

In the below script tbl_discount_coupon table contains the available token with the corresponding discount amount.

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);

CREATE TABLE `tbl_discount_coupon` (
  `id` int(8) NOT NULL,
  `discount_code` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_discount_coupon`
--

INSERT INTO `tbl_discount_coupon` (`id`, `discount_code`, `price`) VALUES
(1, 'C_USB02', 100.00),
(2, 'C_LPN45', 200.00),
(3, 'C_3DcAM01', 340.00),
(4, 'C_wristWear03', 50.00);

eCommerce Software with discount option Output

The screenshot shown below shows total shopping cart item price, applied discount amount and the total amount after applying the discount. The Apply Discount button click event will submit the entered discount and make the calculation to compute the net amount. Thus your eCommerce software gets a complete discount functionality.

How to develop eCommerce software with discount coupon

Conclusion

As we have seen in this article, discount is one of the most attracting factor for the customers using a eCommerce software. Regardless of the online offline shopping people loves discount offers. So, adding this feature in your PHP shopping cart software will increase the customer in-flow and thereby the sales.

With this discount offers, the seller used to apply tricks and tactics to make the deal win-win to both the seller and buyer. For example, by making the discount applicable from some amount range or some high value products and more.

Discount amount will be fixed or in the for of percentage. If it is fixed, then the application code should have the catch not to allow the discount to go high compare to the purchase amount.

In this example, I have used fixed discount amount mapped and managed with the  coupon code using database. If the discount amount exceeded the limit then it will not applied on the total.

This example is planned with a simple logic on discount system implementation. For a full fledged eCommerce software we can enhance the discount coupon implementation further with single-multi time usage constraints, product based discount constraints and more.

With this round coverage about implementation and  advantages of eCommerce software with discount, it will be simple and easy to integrate discount system in your shopping cart.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Develop eCommerce Software with Discount Coupon”

Leave a Reply to Knight Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page