Skip to main content

Generating Coupon Code in PHP Tutorial

Screenshot
Body

In this tutorial we will create Generate Coupon Code using PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by a newly coders for its user-friendly environment.

So let's now do the coding...

Getting Started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html.

And this is the link for the jquery that i used in this tutorial https://jquery.com/.

Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_coupon, after that click Import then locate the database file inside the folder of the application then click ok.

tut1

Or you can create the database tables and columns programmatically. To do that, navigate to your database SQL Tab in PHPMyAdmin and paste the SQL Script below.

  1. CREATE TABLE `coupon` (
  2. `coupon_id` int(11) NOT NULL,
  3. `coupon_code` varchar(20) NOT NULL,
  4. `discount` int(10) NOT NULL,
  5. `status` varchar(10) NOT NULL
  6.  
  7. CREATE TABLE `product` (
  8. `product_id` int(11) NOT NULL,
  9. `product_name` varchar(50) NOT NULL,
  10. `product_price` int(20) NOT NULL,
  11. `product_image` varchar(100) NOT NULL
  12.  
  13. ALTER TABLE `coupon`
  14. ADD PRIMARY KEY (`coupon_id`);
  15.  
  16. ALTER TABLE `product`
  17. ADD PRIMARY KEY (`product_id`);
  18.  
  19. ALTER TABLE `coupon`
  20. MODIFY `coupon_id` int(11) NOT NULL AUTO_INCREMENT;
  21. --
  22. -- AUTO_INCREMENT for table `product`
  23. --
  24. ALTER TABLE `product`
  25. MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT;

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

  1. <?php
  2. $conn = mysqli_connect('localhost', 'root', '', 'db_coupon');
  3.  
  4. if(!$conn){
  5. die("Error: Failed to connect to database");
  6. }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write them into your text editor, then save them as shown below.

index.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1" />
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Generate Coupon Code</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#form_coupon"><span class="glyphicon glyphicon-plus"></span> Generate Coupon</button>
  18. <button type="button" class="btn btn-success" data-toggle="modal" data-target="#form_product"><span class="glyphicon glyphicon-plus"></span> Add Product</button>
  19. <br />
  20. <br />
  21. <?php
  22. require 'conn.php';
  23.  
  24. $query = mysqli_query($conn, "SELECT * FROM `product`") or die(mysqli_error());
  25. while($fetch = mysqli_fetch_array($query)){
  26. ?>
  27. <div class="col-md-3" style="border:1px solid #ccc; padding:10px; margin:23px; height:250px;">
  28. <img src="<?php echo $fetch['product_image']?>" width="100%"/>
  29. <center><h5><?php echo $fetch['product_name']?></h5></center>
  30. <center><h5>&#8369;<?php echo number_format($fetch['product_price'])?></h5></center>
  31. <br />
  32. <center><a href="purchase.php?product_id=<?php echo $fetch['product_id']?>" class="btn btn-warning"><span class="glyphicon glyphicon-shopping-cart"></span> Purchase</a></center>
  33. </div>
  34. <?php
  35. }
  36. ?>
  37. </div>
  38. <div class="modal fade" id="form_coupon" tabindex="-1" role="dialog" aria-hidden="true">
  39. <div class="modal-dialog">
  40. <form action="save_coupon.php" method="POST">
  41. <div class="modal-content">
  42. <div class="modal-body">
  43. <div class="col-md-2"></div>
  44. <div class="col-md-8">
  45. <div class="form-group">
  46. <label>Coupon Code</label>
  47. <input type="text" class="form-control" name="coupon" id="coupon" readonly="readonly" required="required"/>
  48. <br />
  49. <button id="generate" class="btn btn-success" type="button"><span class="glyphicon glyphicon-random"></span> Generate</button>
  50. </div>
  51. <div class="form-group">
  52. <label>Discount</label>
  53. <input type="number" class="form-control" name="discount" min="10" required="required"/>
  54. </div>
  55. </div>
  56. </div>
  57. <div style="clear:both;"></div>
  58. <div class="modal-footer">
  59. <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  60. <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  61. </div>
  62. </div>
  63. </form>
  64. </div>
  65. </div>
  66. <div class="modal fade" id="form_product" tabindex="-1" role="dialog" aria-hidden="true">
  67. <div class="modal-dialog">
  68. <form action="save_product.php" method="POST" enctype="multipart/form-data">
  69. <div class="modal-content">
  70. <div class="modal-body">
  71. <div class="col-md-2"></div>
  72. <div class="col-md-8">
  73. <div class="form-group">
  74. <label>Product Name</label>
  75. <input type="text" class="form-control" name="product_name" required="required"/>
  76. </div>
  77. <div class="form-group">
  78. <label>Product Price</label>
  79. <input type="number" class="form-control" name="product_price" min="0" required="required"/>
  80. </div>
  81. <div class="form-group">
  82. <label>Product Image</label>
  83. <input type="file" class="form-control" name="product_image" required="required"/>
  84. </div>
  85. </div>
  86. </div>
  87. <div style="clear:both;"></div>
  88. <div class="modal-footer">
  89. <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  90. <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  91. </div>
  92. </div>
  93. </form>
  94. </div>
  95. </div>
  96.  
  97. <script src="js/jquery-3.2.1.min.js"></script>
  98. <script src="js/bootstrap.js"></script>
  99. <script type="text/javascript">
  100. $(document).ready(function(){
  101. $('#generate').on('click', function(){
  102. $.get("get_coupon.php", function(data){
  103. $('#coupon').val(data);
  104. });
  105. });
  106. });
  107. </script>
  108. </body>
  109. </html>
purchase.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1" />
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Generate Coupon Code</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <a href="index.php" class="btn btn-success">Back</a>
  18. <br />
  19. <h4>Purchase Product</h4>
  20. <?php
  21. require 'conn.php';
  22. $query = mysqli_query($conn, "SELECT * FROM `product` WHERE `product_id` = '$_REQUEST[product_id]'") or die(mysqli_error());
  23. $fetch = mysqli_fetch_array($query);
  24. ?>
  25. <div class="col-md-2"></div>
  26. <div class="col-md-8">
  27. <img src="<?php echo $fetch['product_image']?>" width="100%" height="300px"/>
  28. <center><h3><?php echo $fetch['product_name']?></h3></center>
  29. <center><h4>&#8369;<?php echo number_format($fetch['product_price'])?></h4></center>
  30. <div class="form-group">
  31. <h4 class="text-warning">*Optional</h4>
  32. <label>Coupon Code</label>
  33. <input class="form-control" type="text" id="coupon"/>
  34. <input type="hidden" value="<?php echo $fetch['product_price']?>" id="price"/>
  35. <div id="result"></div>
  36. <br style="clear:both;"/>
  37. <button class="btn btn-primary" id="activate">Activate Code</button>
  38. </div>
  39. <div class="form-group">
  40. <label>Total Price</label>
  41. <input class="form-control" type="number" value="<?php echo $fetch['product_price']?>" id="total" readonly="readonly" lang="en-150"/>
  42. </div>
  43. </div>
  44. </div>
  45. <script src="js/jquery-3.2.1.min.js"></script>
  46. <script src="js/bootstrap.js"></script>
  47. <script>
  48. $(document).ready(function(){
  49. $('#activate').on('click', function(){
  50. var coupon = $('#coupon').val();
  51. var price = $('#price').val();
  52. if(coupon == ""){
  53. alert("Please enter a coupon code!");
  54. }else{
  55. $.post('get_discount.php', {coupon: coupon, price: price}, function(data){
  56. if(data == "error"){
  57. alert("Invalid Coupon Code!");
  58. $('#total').val(price);
  59. $('#result').html('');
  60. }else{
  61. var json = JSON.parse(data);
  62. $('#result').html("<h4 class='pull-right text-danger'>"+json.discount+"% Off</h4>");
  63. $('#total').val(json.price);
  64. }
  65. });
  66. }
  67. });
  68. });
  69. </script>
  70. </body>
  71. </html>

Creating PHP Query

This code contains the PHP query of the application. This code is consists of several functionalities, it will save the data to the database server and display a discounted price. To do that just copy and write this block of codes inside the text editor, then save it as shown below.

save_product.php
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['save'])){
  5. $product_name = $_POST['product_name'];
  6. $product_price = $_POST['product_price'];
  7. $image_name = $_FILES['product_image']['name'];
  8. $image_temp = $_FILES['product_image']['tmp_name'];
  9. $image_size = $_FILES['product_image']['size'];
  10.  
  11.  
  12. if($image_size > 500000){
  13. echo "<script>alert('File too large to upload')</script>";
  14. echo "<script>window.location = 'index.php'</script>";
  15. }else{
  16. $file = explode(".", $image_name);
  17. $file_ext = end($file);
  18. $ext = array("png", "jpg", "jpeg");
  19.  
  20. if(in_array($file_ext, $ext)){
  21. $location = "upload/".$image_name;
  22. if(move_uploaded_file($image_temp, $location)){
  23. mysqli_query($conn, "INSERT INTO `product` VALUES('', '$product_name', '$product_price', '$location')") or die(mysqli_error());
  24. echo "<script>alert('Product Saved!')</script>";
  25. echo "<script>window.location = 'index.php'</script>";
  26. }
  27. }else{
  28. echo "<script>alert('Only images allowed')</script>";
  29. echo "<script>window.location = 'index.php'</script>";
  30. }
  31. }
  32.  
  33.  
  34. }
  35. ?>
save_coupon.php
  1. <?php
  2. require_once 'conn.php';
  3. if(ISSET($_POST['save'])){
  4. $coupon_code = $_POST['coupon'];
  5. $discount = $_POST['discount'];
  6. $status = "Valid";
  7. $query = mysqli_query($conn, "SELECT * FROM `coupon` WHERE `coupon_code` = '$coupon_code'") or die(mysqli_error());
  8. $row = mysqli_num_rows($query);
  9.  
  10. if($row > 0){
  11. echo "<script>alert('Coupon Already Use')</script>";
  12. echo "<script>window.location = 'index.php'</script>";
  13. }else{
  14. mysqli_query($conn, "INSERT INTO `coupon` VALUES('', '$coupon_code', '$discount', '$status')") or die(mysqli_error());
  15. echo "<script>alert('Coupon Saved!')</script>";
  16. echo "<script>window.location = 'index.php'</script>";
  17. }
  18. }
  19. ?>
get_discount.php
  1. <?php
  2. require_once 'conn.php';
  3. $coupon_code = $_POST['coupon'];
  4. $price = $_POST['price'];
  5.  
  6. $query = mysqli_query($conn, "SELECT * FROM `coupon` WHERE `coupon_code` = '$coupon_code' && `status` = 'Valid'") or die(mysqli_error());
  7. $count = mysqli_num_rows($query);
  8. $fetch = mysqli_fetch_array($query);
  9. $array = array();
  10. if($count > 0){
  11. $discount = $fetch['discount'] / 100;
  12. $total = $discount * $price;
  13. $array['discount'] = $fetch['discount'];
  14. $array['price'] = $price - $total;
  15.  
  16. echo json_encode($array);
  17.  
  18. }else{
  19. echo "error";
  20. }
  21. ?>

Creating the Main Function

This code contains the main function of the application. This code will generate a random coupon code that will be use when getting a discounted price. To make this just follow and write the below inside the text editor, then save it as get_coupon.php
  1. <?php
  2. function coupon($l){
  3. $coupon = "PR".substr(str_shuffle(str_repeat('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',$l-2)),0,$l-2);
  4.  
  5. return $coupon;
  6. }
  7.  
  8. echo coupon(10);
  9. ?>

DEMO

There you have it we successfully created Generate Coupon Code using PHP. I hope that this simple tutorial helps you to what you are looking for. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!!

Comments

Add new comment