DEV Community

Cover image for Coupon Code Generator in PHP and MySQL using Ajax and jQuery
Code And Deploy
Code And Deploy

Posted on • Edited on

Coupon Code Generator in PHP and MySQL using Ajax and jQuery

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/coupon-code-generator-in-php-and-mysql-using-ajax-and-jquery

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will show you how to create a basic coupon code functionality generator and save it to our database and redeem it with the user. If you build a project about E-commerce this functionality is important to share coupon codes to your customer and get a discount.

coupon-code-generator-in-php-and-mysql-using-ajax-and-jquery

coupon-code-generator-in-php-and-mysql-using-ajax-and-jquery

But take note this is basic functionality only the following below is how it works.

  1. Generate coupon code
  2. Check if not yet existing in our database
  3. If not yet existing then store it in our database with a 1 value in the status field
  4. Then our 2nd feature is to redeem the coupon code then check if still active
  5. If active then the server will message that the coupon code is successfully redeemed and update the coupon code to inactive so that it will not usable to the other customers.

That's it now I will show the step by step on how to code it.

1. Create Database

You will need to create your database first in any name you want. Just open your command prompt and do the process using MySQL command for easier just use PHPMyAdmin if you have installed it already at your localhost.

2. Create Table

Then run this SQL named "coupons" table.



CREATE TABLE `coupons` (
  `id` int(10) NOT NULL,
  `name` varchar(25) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `coupons`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `coupons`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;


Enter fullscreen mode Exit fullscreen mode

3. Setup Database Connection

Following code below is our config.php file at available download source code we define our database credentials here.



<?php
    //set the servername
    define("SERVER_NAME", "localhost");
    //set the server username
    define("SERVER_UNAME", "root");
    // set the server password (you must put password here if your using live server)
    define("SERVER_UPASS", "");
    // set the database name
    define("SERVER_DB", "demos");

    // Include functions file
    require_once 'functions.php';

    // Set a variable $db and store db connection
    $db = connectDB();
?>


Enter fullscreen mode Exit fullscreen mode

4. Function to Generate Coupon Code

In the following code below we use it to generate our coupon code, you will find this function inside the functions.php file if you download it.



function couponCodeGenerator() 
{
    $couponGenerated = randomString();

    $attributes = [
        'name' => $couponGenerated
    ];

    // Check if coupon code generated is unique
    if(isRecordUnique($attributes, 'name', 'coupons')):

        // Connect to database
        $db = connectDB();

        // SQL Statement
        $sql = "INSERT INTO coupons (name)
        VALUES (
            '".$couponGenerated."'
        )";

        // Process the query
        if (!$db->query($sql)):
            echo "Error: " . $sql . "<br>" . $db->error;
        endif;

        // Close the connection after using it
        $db->close();

        return $couponGenerated;

    else://if not unique re-call the function and generate again
        couponCodeGenerator();
    endif;
}


function randomString($length = 10) {
    // Set the chars
    $chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Count the total chars
    $totalChars = strlen($chars);

    // Get the total repeat
    $totalRepeat = ceil($length/$totalChars);

    // Repeat the string
    $repeatString = str_repeat($chars, $totalRepeat);

    // Shuffle the string result
    $shuffleString = str_shuffle($repeatString);

    // get the result random string
    return substr($shuffleString,1,$length);
}


Enter fullscreen mode Exit fullscreen mode

5. Call The Function CouponCodeGenerator()

Now we will create our generate-coupon.php file to call our function above couponCodeGenerator() and display results to our client-side functions.



<?php
    // include config file
    require_once 'config.php';

    echo couponCodeGenerator();

?>


Enter fullscreen mode Exit fullscreen mode

6. Next, generateCouponCode() Javascript Function

You will find this function in assets/js/scripts.js file this function will request to the server or the code above to generate the coupon code and display the result coupon code to textbox.



function generateCouponCode() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#generateCouponCodeForm"; //defined the #generateCouponCodeForm ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
               // Insert response generated coupon code
               $(form).find("[name='coupon-code']").val(response);
            },
            complete: function() {
                $this.attr('disabled', false).html($caption);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}


Enter fullscreen mode Exit fullscreen mode

7. PHP Use Coupon Code Function

You will find this code inside the use-coupon.php file it will check the coupon code is still active then redeeming it.



<?php
    // include config file
    require_once 'config.php';

    //a PHP Super Global variable which used to collect data after submitting it from the form
    // Sanitize fist the values of this variable
    $request = sanitize($_REQUEST);

    // Validate the data
    $validation = validate($request, [
        'coupon-code' => 'required|max:25'
    ]);

    // Defined $result as array
    $result = [];

    // Check if no validation errors
    if(!count($validation)):

        // Connect to database
        $db = connectDB();

        // Set the INSERT SQL data
        $sql = "SELECT * FROM coupons WHERE name='".$request['coupon-code']."' AND status='1'";

        // Process the query
        $results = $db->query($sql);

        // Fetch Associative array
        $row = $results->fetch_assoc();

        // Check if coupon code still active
        if(!is_null($row)):
            // Set the UPDATE SQL data for coupon code to inactive after using it
            $sql = "UPDATE coupons SET status='0' WHERE id='".$row['id']."'";

            // Process the query
            if ($db->query($sql)) {
                $result['response'] = "Coupon code succesfully redeemed.";
            } else {
                $result['response'] = "Error: " . $sql . "<br>" . $db->error;
            }
        else:
            $result['has_error'] = 1;
            $result['errors']['coupon-code'] = [
                "used" => "Coupon code is already in used."
            ];
        endif;

        // Close the connection after using it
        $db->close();
    else:
        $result['has_error'] = 1;
        $result['errors'] = $validation;
    endif;

    // Encode array into json format
    echo json_encode($result);


?>


Enter fullscreen mode Exit fullscreen mode

8. Javascript Use Coupon Code Function

In this function, we will redeem the coupon code and display error/success message after processing it. You will find this useCouponCode() function inside assets/js/scripts.js file.



function useCouponCode() 
{
    $("#btnUseCouponCode").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#useCouponCodeForm"; //defined form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
               response = JSON.parse(response);

                // Check if there is no validation error
                if(!response.hasOwnProperty('has_error')) {

                    // We will display the result using alert
                    Swal.fire({
                      icon: 'success',
                      title: 'Success.',
                      text: response.response
                    });

                    // Reset form
                    resetForm(form);
                } else {
                    // We will display the result using alert
                    validationForm(form, response.errors);
                }
            },
            complete: function() {
                $this.attr('disabled', false).html($caption);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}


Enter fullscreen mode Exit fullscreen mode

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Now you have the basic functionality on how to create coupon codes that are available to redeem to your customers. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/coupon-code-generator-in-php-and-mysql-using-ajax-and-jquery if you want to download this code.

Happy coding :)

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.