Author

Ankit Prajapati

Browsing

Hello folks,
You might have seen the feature of Load More. If you want to develop such a feature as “Load more data using jQuery” then you are in right place. You check this demo also before starting to code.

It can be for anything like load more products if you are in e-commerce website, It can be load more post you are visiting any blog website or in general, it can be load more records.
It’s a kind of pagination, yes but it will have a Load More button instead pagination links or page numbers. We will talk about other pagination as well in the upcoming article. For now, we will develop this as a Load more option. However, if you want to check we already have a similar article.

Check Also: How to integrate data table plugin in HTML and CSS

DataTable is a plug-in for the jQuery JavaScript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table

In this post, we are going to implement a kind of pagination called Load More. We will load Quotes. 
By default, we will load 2 quotes in this example but you can define the number in the constant file or customize this solution as per your requirement.

Now when you click on the Load more button it will load another 2 quotes and append them to the current list. This process will go so on and so far until there are no remaining quotes. The load more button will be hidden if there are no more quotes remaining to load. So let’s start to develop load more data using jQuery, and AJAX.

Step 1: Database Setup

Since we are fetching all quotes/records from the database first of all we need to set up the database. Create a database, and create a table “bird_quotes” because we take this table name in code. In the next section, you will get the SQL query for the same.

Step 2: Code & Files setup

Now we need to create these files as shown in the below screenshot, I will explain the purpose of these files. Now let’s create code for each file and understand the purpose also.

Step 3: Lets code

constant.php

The purpose of creating this is to store database credentials & pagination settings. In the third part of this article, we considered loading 2 records each time. So this number can be changed from the constant.php file

<?php
/**
 * Database configuration
 */
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'codingbirds');

/**
 * Define no. of records to be load each time
 */
define('PER_PAGE', 2);

Database.php

This file is a PHP class of database connection. As you know we require a database connection with PHP, So here is the code for this file.

<?php
include_once "constants.php";
class Database
{
    /**
     * @var mysqli
     */
    public $connection;

    public function __construct()
    {
        $this->connection = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
        if (!$this->connection) {
            die("Error in database connection". $this->connection->connect_error);
        }
    }
}

index.php

This index.php is the main file that gets loaded and shows the 2 quotes by default and shows “ajax load more” button UI. Below is the code for this file.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>How to load more records using php, mysql & AJAX - Coding Birds Online</title>
    <style> .blockquote  { font-size: 1.1rem !important; }</style>
</head>
<body>
<div class="container">
   <div class="mt-3 mb-3">
       <center>
           <img src="https://codingbirdsonline.com/wp-content/uploads/2020/01/cropped-coding-birds-online-favicon-180x180.png" width="50"/>
       </center>
   </div>
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div id="quotes-container"></div>
            <input type="hidden" id="page" value="0"/>
            <button
                type="button"
                id="load-more-btn"
                onclick="loadMoreQuotes();"
                class="btn btn-sm btn-success btn-block"
                >Load more...
                <div id="loading" class="spinner-border spinner-border-sm d-none" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
            </button>
        </div>
    </div>
    <div class="row">
        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- middle-ads -->
        <ins class="adsbygoogle"
             style="display:block"
             data-ad-client="ca-pub-5191137430270102"
             data-ad-slot="7861133754"
             data-ad-format="auto"
             data-full-width-responsive="true"></ins>
        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
    </div>
</div>
<script src="load-more-quotes.js"></script>
</body>
</html>

load-more-quotes.js

This file contains JavaScript & jQuery logic to load more data. loadMoreQuotes( ) function is called the first time automatically when the page load, later it is called with the click of a button.

$(document).ready(function(){
    /**
     * Call load quotes as soon as page ready
     */
    loadMoreQuotes();
});
function loadMoreQuotes(){
    let page = parseInt($("#page").val());
    page = page + 1;
    let quotesHtml = ``;
    $.ajax({
        url: "load-more-script.php",
        method: "POST",
        data: {
            request_name: "load-more-quotes",
            page: page,
        },
        beforeSend: function(){
            /**
             * Show the loading icon in load more button
             */
            $("#loading").removeClass('d-none');
        },
        success: function (response){
            /**
             * Prepare the html of quotes
             * @type {any}
             */
            response = JSON.parse(response);
            let quotes = response.data;
            if(quotes.length > 0) {
                $.each(quotes, function (key, value) {
                    quotesHtml += `<div class="card card-signin my-3">
                                    <div class="card-body">
                                        <blockquote class="blockquote mb-0">
                                            <p>${value.quote}</p>
                                            <footer class="blockquote-footer">Someone famous in <cite title="Source Title">${value.author}</cite></footer>
                                        </blockquote>
                                    </div>
                                </div>`;
                });
                /**
                 * Update the page page number to track the no. of calls
                 * Append quotes html prepared to div
                 * Conditionally show/hide the load more button
                 */
                $("#page").val(page);
                $("#quotes-container").append(quotesHtml);
                if (response.remaining_quotes == 0) {
                    $("#load-more-btn").hide();
                }
            }
        },
        error: function(errorResponse){
            console.error(errorResponse)
        },
        complete: function(){
            /**
             * Hide loading icon each time when api call completes
             */
            $("#loading").addClass('d-none');
        }
    })
}

load-more-script.php

This file is a PHP script file to perform our load more pagination from the backend. It returns the response in the form of JSON.

<?php
require_once "constants.php";
require_once "Database.php";
require_once "Quote.php";
/**
 * Prepares the Database, Quote class objects
 */
$db = new Database();
$quote = new Quote();
if (isset($_POST['request_name'])){
    if($_POST['request_name'] == 'load-more-quotes'){
        /**
         * Make the offset, limit
         */
        $offset = ($_POST['page'] - 1) * PER_PAGE;
        $limit = PER_PAGE;
        $quotesData = array();
        $pagination = array(
            'offset' => $offset,
            'limit' => $limit,
        );
        $quotes = $quote->loadQuotes($db->connection, $pagination);
        $totalQuotes = $quote->totalQuotes($db->connection);
        if($quotes){
            while ($quote = $quotes->fetch_object()){
                $quotesData[] = $quote;
            }
        }
        echo json_encode(array(
            'data' => $quotesData,
            'remaining_quotes' => $totalQuotes - PER_PAGE * $_POST['page'],
        ));
    }
}

Quote.php

This is a PHP class file which two functions to load the quotes and count total quotes respectively.

<?php
class Quote
{
    /**
     * Load the quotes based on limit. offset
     * @param $connection
     * @param $pagination
     * @return object
     */
    public function loadQuotes($connection, $pagination)
    {
        $query = "SELECT * FROM bird_quotes LIMIT ". $pagination['offset']. ",". $pagination['limit'];
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result;
    }

    /**
     * Calculates the total quotes in database
     * @param $connection
     * @return int
     */
    public function totalQuotes($connection)
    {
        $query = "SELECT COUNT(*) FROM bird_quotes as quotes_count";
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result->fetch_row()[0];
    }
}

SQL code to create table

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 10, 2022 at 08:44 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `codingbirds`
--

-- --------------------------------------------------------

--
-- Table structure for table `bird_quotes`
--

CREATE TABLE `bird_quotes` (
  `id` int(11) NOT NULL,
  `quote` text NOT NULL,
  `author` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `bird_quotes`
--

INSERT INTO `bird_quotes` (`id`, `quote`, `author`) VALUES
(1, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(2, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(3, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(4, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(5, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(6, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(7, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(8, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(9, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(10, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `bird_quotes`
--
ALTER TABLE `bird_quotes`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `bird_quotes`
--
ALTER TABLE `bird_quotes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 4: Run the code

Congrats! now you have reached the final step to run the code & get your desired output. As you navigate this localhost URL to your browser you will get something like as below.

Now if you want to load more quotes, just click on the button you will get 2 more quotes without page refresh since we are using AJAX. Why 2 quotes because we defined this value in the constants.php file, you can change it according to your needs.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also before starting to code.

Conclusion

I hope you learned what I explained in the above steps, If you have any suggestions are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find it useful which gives me the motivation to create such content.

Hellowww friends! after a long time I am back again with another post. Today I have come with stripe Payment Gateway Tutorial. So let’s start the post. Let’s talk about stripe payment gateway integration.

Stripe is one of the most used payment gateway used across the world. It is a cloud payment gateway platform that helps to accept and manage online transactions anywhere in the world. It provides complete solutions to process online payments and also offers great features like a custom UI toolkit, embeddable checkout, consolidated reports, and much more.

To start payment gateway integration in PHP you need to have a merchant/owner account in stripe means if you have a business or any e-commerce website and want to accept online payment then you need to have an owner account. You can create and upload other verifications details like bank account and identity details. I hope you have completed these steps and just looking for code and procedure to integrate. So let’s move to the next step. Check this demo.

Check also: Razorpay Payment Gatway Integration

Get your API keys

Login to your stripe dashboard, go to the right top corner under the profile dropdown you will see the developer link. Find the secret key and copy keep it somewhere we are going to use it.

Project & Code Setup

Now we need an official Stripe PHP library. If you composer then it’s fine otherwise we need to install the composer. Composer is a dependency manager tool. Click here to download it from the composer website and install it. It is very simple to install. Now create a project folder in your xampp/wampp project directory.

After you have created the project folder, open CMD inside the project directory and run the below command.

Stripe payment gateway integration

Install Stripe PHP Library

composer require stripe/stripe-php

After your command completes it will create a vendor folder, composer.json & composer.lock files. We don’t need to touch these files. Now rest of the files we need to create our project directory.

integrate-stripe-payment-gateway-in-files-directory-php-coding-birds-online

index.php is the home page which is the simple event registration & fee payment form. This is we are going to have a number of registrations and accept fees via stripe. Here is the code of this file.

Database Setup

To keep the number of registrations and payment status we need to create a database. In this case database name is “codingbirds” and the table is called “bird_stripe_payments

After creating the database go to SQL and paste this code and run to create the table.

--
-- Table structure for table `bird_stripe_payments`
--
CREATE TABLE `bird_stripe_payments` (
  `id` int(10) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `contact` varchar(12) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `payment_status` enum('Pending','Completed') NOT NULL DEFAULT 'Pending',
  `payment_intent` text DEFAULT NULL,
  `created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Code & Files Setup

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>How to integrate stripe payment gateway in php - Coding Birds Online</title>
    <style> .required { color: red; font-weight: bold }</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center>
                        <img src="https://codingbirdsonline.com/wp-content/uploads/2020/01/cropped-coding-birds-online-favicon-180x180.png" width="50"/>
                    </center> <br/>
                    <h5 class="card-title text-center">Join This College Event</h5>
                    <form action="checkout.php" method="post">
                        <div class="form-group">
                            <label for="name">Name <span class="required">*</span></label>
                            <input type="text" name="name" class="form-control" placeholder="Name" required/>
                        </div>
                        <div class="form-group">
                            <label for="email">Email <span class="required">*</span></label>
                            <input type="email" name="email" id="email" class="form-control" placeholder="Email" required/>
                        </div>
                        <div class="form-group">
                            <label for="contact">Contact <span class="required">*</span></label>
                            <input type="text" name="contact" id="contact" class="form-control" placeholder="Contact" maxlength="10" required/>
                        </div>
                        <div class="form-group">
                            <label for="amount">Fee Amount <span class="required">*</span></label>
                            <input type="text" name="amount" id="amount" class="form-control" placeholder="Amount" value="100" readonly required/>
                        </div>
                        <button type="submit" name="payNowBtn" class="btn btn-lg btn-primary btn-block">Pay Now <span class="fa fa-angle-right"></span></button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

In the index.php file, we have the form action of checkout.php. This file contains the main logic of creating products and prices and creates payment links and redirects. Here is the code.

<?php
session_start();

require_once 'Database.php';
require_once "StripeHelper.php";
require_once "User.php";
/**
 * APP url/base url
 */
$appUrl = "http://localhost/projects/codingbirds_/integrate-stripe-payment-gateway-in-php/";

$productPrice = 100; // calculate as per logic //

$database = new Database();
/**
 * When registration form submitted
 */
if (isset($_POST['payNowBtn'])){
    $user = new User();
    $data = $_POST;
    $data['amount'] = $productPrice;
    $user = $user->registerUser($database->connection, $_POST);
    $_SESSION['user_id'] = $database->connection->insert_id;
}

$stripeHelper = new StripeHelper();
$stripe = $stripeHelper->stripeClient;
/**
 * Create product
 */
$product = $stripeHelper->createProducts();
/**
 * Create price for product
 */
$price = $stripeHelper->createProductPrice($product, $productPrice);
/**
 * create checkout session and payment link
 */
$stripeSession = $stripe->checkout->sessions->create(
    array(
        'success_url' => $appUrl . 'success.php?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url' => $appUrl . 'failed.php',
        'payment_method_types' => array('card'),
        'mode' => 'payment',
        'line_items' => array(
            array(
                'price' => $price->id,
                'quantity' => 1,
            )
        )
    )
);
header("Location: " . $stripeSession->url);

In this file, we have included other helper class files Database.php, StripeHelper.php & User.php. Here is the code of these files.

Database.php

<?php
include_once "constants.php";
class Database
{
    /**
     * @var mysqli
     */
    public $connection;

    public function __construct()
    {
        $this->connection = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
        if (!$this->connection) {
            die("Error in database connection". $this->connection->connect_error);
        }
    }
}

constants.php file code is

<?php
/**
 * Database configuration
 */
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'codingbirds');

/**
 * Stripe API configuration
 */
define('STRIPE_API_SECRET_KEY', 'xxxxxxxxxxx');

StripeHelper.php

<?php
require 'vendor/autoload.php';
include_once "constants.php";
class StripeHelper
{
    /**
     * @var \Stripe\StripeClient
     */
    public $stripeClient;

    public function __construct()
    {
        $this->stripeClient = new \Stripe\StripeClient(STRIPE_API_SECRET_KEY);
    }
    /**
     * Create product
     * @return \Stripe\Product
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function createProducts()
    {
        return $this->stripeClient->products->create(array(
            'name' => 'Course 1',
            'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
        ));
    }

    /**
     * Create price
     * @param $product
     * @param $productPrice
     * @return \Stripe\Price
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function createProductPrice($product, $productPrice)
    {
        return $this->stripeClient->prices->create(array(
            'unit_amount' => $productPrice * 100,
            'currency' => 'INR',
            'product' => $product->id,
        ));
    }
    /**
     * Get session detail
     * @param $sessionId
     * @return \Stripe\Checkout\Session
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function getSession($sessionId)
    {
        return $this->stripeClient->checkout->sessions->retrieve($sessionId);
    }
}

success.php

<?php
session_start();
require_once "Database.php";
require_once "StripeHelper.php";
require_once "User.php";

$stripeHelper = new StripeHelper();
if(isset($_SESSION['user_id'])){
    $user = new User();
    $database = new Database();
    $sessionId = $_GET['session_id'];
    $userId = $_SESSION['user_id'];
    $checkoutSession = $stripeHelper->getSession($sessionId);
    $user->updatePaymentStatus($database->connection, $checkoutSession->payment_intent, $userId);
}else{
    header("Location: index.php");
}

//echo '<pre>';
///print_r($checkoutSession);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Success | How to integrate stripe payment gateway in php - Coding Birds Online</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body" style="outline: 2px solid #23e323">
                    <h5 class="card-title text-center">Payment success</h5>
                    <p>Transaction ID: <?php echo $checkoutSession->payment_intent; ?> </p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

failed.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Failed | How to integrate stripe payment gateway in php - Coding Birds Online</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
                <div class="card card-signin my-5">
                    <div class="card-body" style="outline: 2px solid red">
                        <h5 class="card-title text-center">Payment failed</h5>
                    </div>
                </div>
                <a href="./index.php" class="btn btn-primary">Try again </a>
            </div>
        </div>
    </div>
</body>
</html>

User.php

<?php
class User
{
    /**
     * Register the user
     * @param $connection
     * @param $data
     * @return mixed
     */
    public function registerUser($connection, $data)
    {
        $date = date('Y-m-d H:i:s');
        $query = "INSERT INTO bird_stripe_payments SET name ='{$data['name']}',email='{$data['email']}',
        contact='{$data['contact']}',amount='{$data['amount']}', created_at='{$date}' ";
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result;
    }

    /**
     * Update the payment status
     * @param $connection
     * @param $txnId
     * @param $userId
     * @return mixed
     */
    public function updatePaymentStatus($connection, $txnId, $userId)
    {
        $query = "UPDATE bird_stripe_payments SET payment_status='Completed', payment_intent='$txnId' WHERE id='$userId' ";
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result;
    }
}

After creating these files & code if you run your project then it will look something like this.

integrate-stripe-payment-gateway-in-files-demo-page-coding-birds-online

After filling in the details click on pay now you will be redirected to the 3rd party stripe page which will handle the payment come back again to our success or fail callback pages.

integrate-stripe-payment-gateway-in-files-demo-stripe-payment-page-coding-birds-online

This is the payment detail page by stripe. This is under test mode you can enter any email name and proceed. Stripe does provide some test details to test the payment. You can try these.

yourtest@gmail.com 4242 4242 4242 4242 02/25123Ankit Prajapati

After successful payment, you will get redirected to the success.php screen

integrate-stripe-payment-gateway-success-page-coding-birds-online

Yes, we can customize the success page according to the needs and requirements.

If payment failed due to any reason or you canceled the payment then you will be redirected to the failed.php file.

integrate-stripe-payment-gateway-failed-page-coding-birds-online

Meanwhile, If you notice the checkout.php we create an entry to our database table with user details and payment status pending. After successful payment, we update the payment status to be completed to keep our record updated.

db-tables-coding-birds-online

Last but not least you can check all your actual payment transactions and history to your stripe dashboard.

stripe-dashboard-coding-birds-online

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find it useful which gives motivation to me to create such content.

Hi developers, welcome you all in another article on how to make the Razorpay payment gateway setup in CodeIgniter. I hope, you must have integrated other payment gateways like PayUmoney, Paytm payment gateway, etc.

If you didn’t don’t worry follow the steps as I have given you, you will able to achieve without any errors.

Razorpay is the most popular payment gateway in India. Razorpay provides clean, fast,
secure payments services with hassle-free integration with developer-friendly APIs.

So without wasting the time, lets come directly for which you came.
I am expecting you that, you all are up with your Razorpay account, and you got your RAZOR_KEY, RAZOR_SECRET_KEY.

Check this also Login with Google account: using JavaScript OAuth Library

What do we need to Razorpay payment gateway setup?

  • A CodeIgniter project
  • A Controller of which index function will load a form view
  • If you want to save information to the database then you create a model also.
  • We need a form view file
  • Last but not least, follow the steps carefully, don’t worry if your code does not work. I will provide the source code also.

Step 1: Get the keys and define them in the project

Open the “application/config/constants.php” file, at the end of the fine define constants:

  <?php
    define('RAZOR_KEY_ID', 'XXXXXXXXXX');
    define('RAZOR_KEY_SECRET', 'XXXXXXXXXX');
  ?>

Step 2: Create a controller “Register.php”

Got to “application/controllers/” create a PHP file named “Register.php” and paste the following code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once(APPPATH."libraries/razorpay/razorpay-php/Razorpay.php");

use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

class Register extends CI_Controller {
	/**
	 * This function loads the registration form
	 */
	public function index()
	{
		$this->load->view('register');
	}

	/**
	 * This function creates order and loads the payment methods
	 */
	public function pay()
	{
		$api = new Api(RAZOR_KEY, RAZOR_SECRET_KEY);
		/**
		 * You can calculate payment amount as per your logic
		 * Always set the amount from backend for security reasons
		 */
		$_SESSION['payable_amount'] = 10;

		$razorpayOrder = $api->order->create(array(
			'receipt'         => rand(),
			'amount'          => $_SESSION['payable_amount'] * 100, // 2000 rupees in paise
			'currency'        => 'INR',
			'payment_capture' => 1 // auto capture
		));


		$amount = $razorpayOrder['amount'];

		$razorpayOrderId = $razorpayOrder['id'];

		$_SESSION['razorpay_order_id'] = $razorpayOrderId;

		$data = $this->prepareData($amount,$razorpayOrderId);

		$this->load->view('rezorpay',array('data' => $data));
	}

	/**
	 * This function verifies the payment,after successful payment
	 */
	public function verify()
	{
		$success = true;
		$error = "payment_failed";
		if (empty($_POST['razorpay_payment_id']) === false) {
			$api = new Api(RAZOR_KEY, RAZOR_SECRET_KEY);
		try {
				$attributes = array(
					'razorpay_order_id' => $_SESSION['razorpay_order_id'],
					'razorpay_payment_id' => $_POST['razorpay_payment_id'],
					'razorpay_signature' => $_POST['razorpay_signature']
				);
				$api->utility->verifyPaymentSignature($attributes);
			} catch(SignatureVerificationError $e) {
				$success = false;
				$error = 'Razorpay_Error : ' . $e->getMessage();
			}
		}
		if ($success === true) {
			/**
			 * Call this function from where ever you want
			 * to save save data before of after the payment
			 */
			$this->setRegistrationData();

			redirect(base_url().'register/success');
		}
		else {
			redirect(base_url().'register/paymentFailed');
		}
	}

	/**
	 * This function preprares payment parameters
	 * @param $amount
	 * @param $razorpayOrderId
	 * @return array
	 */
	public function prepareData($amount,$razorpayOrderId)
	{
		$data = array(
			"key" => RAZOR_KEY,
			"amount" => $amount,
			"name" => "Coding Birds Online",
			"description" => "Learn To Code",
			"image" => "https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png",
			"prefill" => array(
				"name"  => $this->input->post('name'),
				"email"  => $this->input->post('email'),
				"contact" => $this->input->post('contact'),
			),
			"notes"  => array(
				"address"  => "Hello World",
				"merchant_order_id" => rand(),
			),
			"theme"  => array(
				"color"  => "#F37254"
			),
			"order_id" => $razorpayOrderId,
		);
		return $data;
	}

	/**
	 * This function saves your form data to session,
	 * After successfull payment you can save it to database
	 */
	public function setRegistrationData()
	{
		$name = $this->input->post('name');
		$email = $this->input->post('email');
		$contact = $this->input->post('contact');
		$amount = $_SESSION['payable_amount'];

		$registrationData = array(
			'order_id' => $_SESSION['razorpay_order_id'],
			'name' => $name,
			'email' => $email,
			'contact' => $contact,
			'amount' => $amount,
		);
		// save this to database

	}

	/**
	 * This is a function called when payment successfull,
	 * and shows the success message
	 */
	public function success()
	{
		$this->load->view('success');
	}
	/**
	 * This is a function called when payment failed,
	 * and shows the error message
	 */
	public function paymentFailed()
	{
		$this->load->view('error');
	}	
}

Step 2: Create view files “registration-form.php” and “rezorpay.php”

Got to “application/views/” create two files named “registration-form.php” and “rezorpay.php” and paste the following code respectively.

registration-form.php

<!doctype html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Razorpay Payment Gateway: How to integration Razorpay payment gatway in CodeIgniter,PHP | CodingBirdsOnline</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <h5 class="card-title text-center">Razor Pay Integration in CodeIgniter</h5>
                    <form action="<?php echo base_url().'register/pay'; ?>" method="post" class="form-signin">
                        <div class="form-label-group">
                            <label for="name">Name <span style="color: #FF0000">*</span></label>
                            <input type="text" name="name" id="name" class="form-control" placeholder="Name"  required >
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="email">Email <span style="color: #FF0000">*</span></label>
                            <input type="text" name="email" id="email" class="form-control" placeholder="Email address" required>
                        </div> <br/>
                        <label for="contact">Contact <span style="color: #FF0000">*</span></label>
                        <div class="form-label-group">
                            <input type="text" id="contact" name="contact" class="form-control" placeholder="Contact" required>
                        </div><br/>

					<label for="subject">Amount <span style="color: #FF0000">*</span></label>
                        <div class="form-label-group">
                            <input type="text" id="amount" name="amount" value="10" readonly class="form-control" placeholder="Amount" required>
                        </div><br/>
                       <br/>
                        <button type="submit" name="sendMailBtn" class="btn btn-lg btn-primary btn-block text-uppercase" >Pay Now</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

rezorpay.php

<button id="rzp-button1" style="display:none;">Pay with Razorpay</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js"></script>
<form name='razorpayform' action="<?php echo base_url().'register/verify';?>" method="POST">
    <input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
    <input type="hidden" name="razorpay_signature"  id="razorpay_signature" >
</form>
<script>
// Checkout details as a json
var options = <?php echo json_encode($data);?>;

/**
 * The entire list of Checkout fields is available at
 * https://docs.razorpay.com/docs/checkout-form#checkout-fields
 */
options.handler = function (response){
    document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;
    document.getElementById('razorpay_signature').value = response.razorpay_signature;
    document.razorpayform.submit();
};

// Boolean whether to show image inside a white frame. (default: true)
options.theme.image_padding = false;

options.modal = {
    ondismiss: function() {
        console.log("This code runs when the popup is closed");
    },
    // Boolean indicating whether pressing escape key 
    // should close the checkout form. (default: true)
    escape: true,
    // Boolean indicating whether clicking translucent blank
    // space outside checkout form should close the form. (default: false)
    backdropclose: false
};

var rzp = new Razorpay(options);

$(document).ready(function(){
	$("#rzp-button1").click();
	 rzp.open();
    e.preventDefault();
});
</script>

Step 3: Run the code

Now the final step is to run the code. For this navigate to your project folder via localhost. If you see the following screen view then congratulations.

Razorpay payment gateway setup

This is just a dummy payment amount, the actual payment you will calculate by your logic. Anyways fill the form and submit it. Now you will a payment screen itself provided by Razorpay and defined its view in the “Application/views/razorpay.php” file.

Razorpay payment gateway setup

Now, this is a dummy payment view, you can make payment by any method you want. In my example, I just selected net banking, click next

Razorpay payment gateway setup

As I already told you that this is a fake payment, so just click on the success button. After that, you will be redirected to a payment success page.

Razorpay payment gateway setup

Source Code & Demo

You can download the full 100% working source code from here.

Conclusion

I hope you learned and understood the Razorpay payment gateway setup explained above, If you have any suggestions, are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find code useful.

Happy Coding 🙂

Hi, If you are looking for the PHP script to learn how to send email with attachment in PHP without going to spam then you are in the right place. I know you searched a lot on Google to find source code but every code sends that to spam, not in the inbox. Check our demo to confirm.

Here I am going to give a PHP script by which your email with an attachment will always go to inbox. Sending an email with attachment is the most common task in web development.

When you are applying for a job or submitting any application, you often might be noticed that they accept a file to upload. It may be anything like your CV or resume, profile picture or any other document.

Sending details to email is sometimes good in terms of saving space on our server. Since we are not storing the details on our database or attachment to our server folders.

How to do that?

Here we will use a simple HTML form accepting basic details like name, email, subject, message, and an attachment. The attachment has a validation that only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload. In the previous tutorial, we learned about how to send email in PHP step by step but here we will do the same with attachment.

So what are we waiting for? Let’s start. Check the files and folder we are going to create.

how-to-send-email-with-attachment-in-php-coding-birds-online-file-and-folders
  • index.php is the main file which is a simple HTML form as I told above.
  • email-script.php is the script file that sends an email with an attachment.
  • validation-script.js is a javaScript validation file.
  • uploads folder saves the attachment to send emails and deletes later.

Now we should create these files. I am giving you just code block here. Make sure you put these CDN in to head off your index.php to work your code.

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

And include this javaScript validation file also before closing to the body tag.

<script src="validation-script.js"></script>

index.php

    <div class="container">
        <div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="../website/img/coding-birds-online/coding-birds-online-favicon.png" width="70"></center>
                        <h5 class="card-title text-center">Send email with attachment in PHP</h5>
                        <form method="post" action="email-script.php" enctype="multipart/form-data" id="emailForm">
                            <div class="form-group">
                                <input type="text" name="name" id="name" class="form-control" placeholder="Name" >
                                <div id="nameError" style="color: red;font-size: 14px;display: none">nameError</div>
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" id="email" class="form-control" placeholder="Email address" >
                                <div id="emailError" style="color: red;font-size: 14px;display: none">emailError</div>
                            </div>
                            <div class="form-group">
                                <input type="text" name="subject" id="subject" class="form-control"  placeholder="Subject" >
                                <div id="subjectError" style="color: red;font-size: 14px;display: none">subjectError</div>
                            </div>
                            <div class="form-group">
                                <textarea name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
                                <div id="messageError" style="color: red;font-size: 14px;display: none">messageError</div>
                            </div>
                            <div class="form-group">
                                <input type="file" name="attachment" id="attachment" class="form-control">
                                <div id="attachmentError" style="color: red;font-size: 14px;display: none">attachmentError</div>
                            </div>
                            <div class="submit">
                                <input type="submit" name="submit" onclick="return validateEmailSendForm();" class="btn btn-success" value="SUBMIT">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

If you notice this form uses an action to email-script.php this file. Create this file also.

email-script.php

<?php

if(isset($_POST['submit'])){
    // Get the submitted form data
    $email = $_POST['email'];
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $uploadStatus = 1;

    // Upload attachment file
    if(!empty($_FILES["attachment"]["name"])){

        // File path config
        $targetDir = "uploads/";
        $fileName = basename($_FILES["attachment"]["name"]);
        $targetFilePath = $targetDir . $fileName;
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

        // Allow certain file formats
        $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
        if(in_array($fileType, $allowTypes)){
            // Upload file to the server
            if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
                $uploadedFile = $targetFilePath;
            }else{
                $uploadStatus = 0;
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }else{
            $uploadStatus = 0;
            $statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
        }
    }

    if($uploadStatus == 1){
        // Recipient
        $toEmail = $email;
        // Sender
        $from = 'info@codingbirdsonline.com';
        $fromName = 'Coding Birds Online';
        // Subject
        $emailSubject = 'Email attachment request Submitted by '.$name;
        // Message
        $htmlContent = '<h2>Contact Request Submitted</h2>
                <p><b>Name:</b> '.$name.'</p>
                <p><b>Email:</b> '.$email.'</p>
                <p><b>Subject:</b> '.$subject.'</p>
                <p><b>Message:</b><br/>'.$message.'</p>';

        // Header for sender info
        $headers = "From: $fromName"." <".$from.">";

        if(!empty($uploadedFile) && file_exists($uploadedFile)){
            // Boundary
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
            // Headers for attachment
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
            // Multipart boundary
            $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
            // Preparing attachment
            if(is_file($uploadedFile)){
                $message .= "--{$mime_boundary}\n";
                $fp =    @fopen($uploadedFile,"rb");
                $data =  @fread($fp,filesize($uploadedFile));
                @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
                    "Content-Description: ".basename($uploadedFile)."\n" .
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }

            $message .= "--{$mime_boundary}--";
            $returnpath = "-f" . $email;
            // Send email
            $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
            // Delete attachment file from the server
            @unlink($uploadedFile);
        }else{
            // Set content-type header for sending HTML email
            $headers .= "\r\n". "MIME-Version: 1.0";
            $headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
            // Send email
            $mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
        }

        // If mail sent
        if($mail){
            $statusMsg = 'Your email attachment request has been submitted successfully !';
        }else{
            $statusMsg = 'Your request submission failed, please try again.';
        }
    }
    echo '<script>alert("'.$statusMsg.'");window.location.href="./";</script>';
}
?>

validation-script.js

function validateEmailSendForm() {
   var name = $("#name").val();
   var email = $("#email").val();
   var subject = $("#subject").val();
   var message = $("#message").val();
   var attachment = $("#attachment").val();

   if (name == ""){
       $("#nameError").show();
       $("#nameError").html("Please enter your name");
       $("#nameError").fadeOut(4000);
       $("#name").focus();
       return false;
   }else  if (email == ""){
       $("#emailError").show();
       $("#emailError").html("Please enter your email");
       $("#emailError").fadeOut(4000);
       $("#email").focus();
       return false;
   }else  if (!validateEmail(email)){
       $("#emailError").show();
       $("#emailError").html("Please enter valid email");
       $("#emailError").fadeOut(4000);
       $("#email").focus();
       return false;
   }else  if (subject == ""){
       $("#subjectError").show();
       $("#subjectError").html("Please enter subject");
       $("#subjectError").fadeOut(4000);
       $("#subject").focus();
       return false;
   }else if (message == ""){
       $("#messageError").show();
       $("#messageError").html("Please enter some message");
       $("#messageError").fadeOut(4000);
       $("#message").focus();
       return false;
   }else if (attachment == ""){
       $("#attachmentError").show();
       $("#attachmentError").html("Please select a attachment");
       $("#attachmentError").fadeOut(4000);
       $("#attachment").focus();
       return false;
   }else{
       return true;
   }

    function validateEmail(inputText) {
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(inputText.match(mailformat)) {
            return true;
        } else{
            return false;
        }
    }
}

Run the code!

Now it is time to run and test our code. If you did everything step by step then you will not face any errors and you will get output something like this.

how-to-send-email-with-attachment-in-php-coding-birds-online-output

This form is validated properly like empty fields, valid email and attachment file accepted. When you fill that form and hit the submit button then you will get the alert message of success or errors.

Check this also How to make a dynamic pie chart in PHP in 2 steps.

Attention !!! It may take 1 or 2 minutes to receive email with attachment so please have patience. But I am sure you will receive in primary inbox not to spam.

how-to-send-email-with-attachment-in-php-coding-birds-online-email-sent-output2
how-to-send-email-with-attachment-in-php-coding-birds-online-email-sent-output3

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Making users active inactive is the most important and common feature in web applications and websites. In this tutorial, we are going to learn how to make active inactive users in PHP using jQuery AJAX without page refresh. You check this demo also. You can implement the same code with CodeIgniter as CI follows the MVC pattern.

Why we need it?

Suppose you have a web application in which employees doing registration and then after login and performs their tasks. Now if any user is doing some inappropriate activities then you disable his login account.

consider this example as you have a list of users or employees and you want to disable his account so that he failed to login. To do this just need to press a thumb down button and his status in the database table will be 0. And In the login query, you make check the only those people can log in to the system whose status is 1.

Check these posts also

So what are you waiting for? let’s get started. Check these files and folder structure.

active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-file-and-folder-structure
  • index.php is the main file on which everything is to be performed
  • script.php is a logic file contains the code to perform active inactive operations
  • script.php uses the config.php is the connection file to the database
  • active-inactive-script.js is the javaScript file in which we wrote AJAX to avoid page refresh
  • bird_active_inactive_users.sql is the SQL file which is a database table which the following structure.
active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-table-structure

Don’t worry I will provide the full 100% working source code so that you can download it and implement it to your machine. Let’s create these files. Make sure you use bootstrap and jQuery. Bootstrap is just for styling and optional but jQuery is mandatory since we are making AJAX request.

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

And include this custom javaScript AJAX request file to the just below to jQuery. Here I am using version 3.4 of jQuery CDN. Here we are using javaScript and jQuery to enhance user experience.

You can learn more about JavaScript functions from this amazing article.

<script src="active-inactive-script.js"></script>

index.php

    <div class="container">
        <div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="../website/img/coding-birds-online/coding-birds-online-favicon.png" width="70"></center>
                        <h5 class="card-title text-center">Active Inactive users in PHP</h5>
                    </div>
                    <table id="exampleTable" class="table table-bordered" style="width: 100%">
                        <thead id="thead">
                        <tr style="background-color: #1573ff">
                            <th>Sr.No</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Contact</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody id="tableBodyData">
                        </tbody>
                    </table>
                    </div>
            </div>
        </div>
   </div>

active-inactive-script.js

$(document).ready(function () {
   $.post("script.php",{key:"getAllUsers"},function (response) {
        $("#tableBodyData").html(response);
   })
});

function activeInactive(recordId,status) {
    var message = ((status == 0?" inactive ":" Active "));
    if (confirm("Are you sure to"+ message+ "the user")){
        $.post("script.php",{key:"activeInactive",status:status,recordId:recordId},function (response) {
            if (response == "success"){
                if (status == 0){
                    $('#activeBtn'+recordId).show();
                    $('#inactiveBtn'+recordId).hide();
                }else if (status == 1){
                    $('#inactiveBtn'+recordId).show();
                    $('#activeBtn'+recordId).hide();
                }
                alert("User is "+ message +"now");
            }
        });
    }
}

script.php

<?php
include "config.php";
if ($_POST['key'] == "getAllUsers") {
    $tableData = '';
    $sr = 1;
    $query = "SELECT * FROM bird_active_inactive_users";
    $result = $connection->query($query);
    if ($result->num_rows>0){
        while ($row = $result->fetch_object()){
            $buttonActive = (($row->status == 0)?'block':'none');
            $buttonInActive = (($row->status == 1)?'block':'none');
            $tableData .='<tr>
                <td>'.$sr.'</td>
                <td>'.$row->name.'</td>
                <td>'.$row->email.'</td>
                <td>'.$row->contact.'</td>
                <td><a href="javaScript:void(0)" title="Active" style="display:'.$buttonActive.'" id="activeBtn'.$row->id.'" onclick="activeInactive(\''.$row->id.'\',1);" class="btn btn-success btn-sm"> <i class="fa fa-thumbs-up"></i></a>
                <a href="javaScript:void(0)" title="In active" style="display:'.$buttonInActive.'" id="inactiveBtn'.$row->id.'" onclick="activeInactive(\''.$row->id.'\',0);" class="btn btn-danger btn-sm"> <i class="fa fa-thumbs-down"></i></a> </td>
            </tr>';
            $sr++;
        }
    }
    echo $tableData;
}

if ($_POST['key'] == "activeInactive"){
    $status = $_POST['status'];
    $recordId = $_POST['recordId'];
    $query = "UPDATE bird_active_inactive_users SET status='$status' WHERE id='$recordId'";
    $result = $connection->query($query);
    if ($result){
        echo "success";
    }
}

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code!

If you followed the steps and you are confident that everything is fine then its time to check the code. Then you will get the output something like this. Create the table and have some data otherwise you will get blank or you can import the same table as I will provide the source code.

active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-output

The red button is to inactive the user and green is to make the user active. Here I haven’t created a login system. This tutorial is to demonstrate how to make active inactive users in PHP using jQuery AJAX.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

To hide email addresses or contact numbers partially is the most common thing in web application development. If you might have noticed on so many websites when you register by using your email id or contact number, then they shoot a verification code on your email or phone.

And you can’t see the full email address or contact. They make it partially hidden by using some stars *. You can check this demo also.

So If you are looking to do the same thing on PHP and looking for how to partially hide email address in PHP using AJAX then you are in the right place.

Check this post also on how to clone a specific folder from a git repository.

How to do?

Here I will use a simple form accepting email id. When you press the submit button you will get a partially hidden email without page refresh.

To do this I will use AJAX functionality so that we can achieve this without page refresh. So without wasting time lets make out hands dirty with code.

  • Create index.php file is the main file
  • Now create script.php file is the logic file to hide email address partially.

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>How to partially hide email address in PHP using AJAX - Coding Birds Online</title>
    <style>.required{color: #FF0000;}</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center><img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"></center>
                    <h5 class="card-title text-center">Partially hide email address in php </h5>
                    <form id="myForm">
                        <div class="form-label-group">
                            <label for="inputEmail">Email <span class="required">*</span></label>
                            <input type="text" name="email" id="email" class="form-control" placeholder="Enter email ">
                        </div><br/>
                        <div id="partiallyHiddenEmail"></div><br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Hide</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
   $("form#myForm").on("submit",function (e) {
       e.preventDefault();
      var email = $("#email").val();
      if (email == ""){
          alert("Please enter email");
          $("#email").focus();
      }else if (!validateEmail(email)){
          alert("Please enter valid email");
          $("#email").focus();
      } else {
          $.post("script.php",{key:"hideEmailAddress",email:email},function (response) {
            $("#partiallyHiddenEmail").html(response);
          });
      }
   });

   function validateEmail(inputText) {
       var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
       if(inputText.match(mailformat)) {
           return true;
       } else{
           return false;
       }
   }
</script>
</body>
</html>

This file uses the AJAX call, which in turn calls the script.php file.

script.php

<?php

if ($_POST['key'] == "hideEmailAddress"){
    $email = $_POST['email'];
    $partiallyHiddenEmail = mask_email($email);
    echo $partiallyHiddenEmail;

}

/*
Here's the logic:

We want to show X numbers.
If length of STR is less than X, hide all.
Else replace the rest with *.

*/

function mask_email($email) {
    $mail_parts = explode("@", $email);
    $domain_parts = explode('.', $mail_parts[1]);

    $mail_parts[0] = mask($mail_parts[0], 2, 1); // show first 2 letters and last 1 letter
    $domain_parts[0] = mask($domain_parts[0], 2, 1); // same here
    $mail_parts[1] = implode('.', $domain_parts);

    return implode("@", $mail_parts);
}

function mask($str, $first, $last) {
    $len = strlen($str);
    $toShow = $first + $last;
    return substr($str, 0, $len <= $toShow ? 0 : $first).str_repeat("*", $len - ($len <= $toShow ? 0 : $toShow)).substr($str, $len - $last, $len <= $toShow ? 0 : $last);
}

Run the Code!

When you run the code you will get something like this. if you get any errors, don’t worry I will provide the full 100% working source code.

how-to-partially-hide-email-address-in-php-using-ajax-coding-birds-online-output-1

If you enter the email address cs.ankitprajapati@gmail.com, Of course, you can enter your own. You will get the following output.

how-to-partially-hide-email-address-in-php-using-ajax-coding-birds-online-output-2

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

If you are looking to learn how to create CRUD application in PHP then you are in the right place. In a web application, 4 operations are mainly performed, Create, Read, Update and Delete. These are called CRUD operations in short.

  • Create – This is to save the data to the database.
  • Read – This is the operation to read or display the saved data from the database.
  • Update – This is to update the existing records in a database.
  • Delete – Last but not least, this is used to perform delete operation in the database.

Each operation has its own query syntax to perform its task. Let’s take a look at each query and we will understand its concepts.

Check this also how to submit form data using AJAX in PHP to learn to perform a single CRUD operation that is to create without page refresh. You check this demo also.

Ultimately we perform CRUD operation in any complex web application or website by different techniques and methods.

Today, I am very happy to share with you CRUD application in PHP using jQuery AJAX from scratch. But today I will show you a very simple way to CRUD using a bootstrap popup model.

How to do that?

In this tutorial, I will use a bootstrap popup model in which I will place a registration form asking to fill name, email, and contact.

After that, I will fetch the records from the database and display them without page refresh that’s why we are using AJAX.

Resources to perform CRUD operations

  • It is mandatory to use jQuery library to use AJAX functionality.
  • Here I will use a popup model on the click of the add button so that we can do this without a page refresh, That’s why we need bootstrap also. This will be good for styling purposes too.
  • That’s enough!

Lets first see the files and folder structure we are going to create for CRUD application in PHP using jQuery AJAX.

crud-application-in-php-using-jquery-ajax-coding-birds-online-files-and-folder-structure

Let’s understand the task of these files. Each file has its own task.

  • config.php is the connection file to the database.
  • crud-app.js is a javaScript file responsible to make AJAX call to accomplish not to page refresh.
  • crud-script.php has the logics of CRUD means to create, read, delete and update.
  • CrudOprations.php is a PHP class that has user-defined functions. Since we are going to use the OOPs methodology.
  • custom.css is CSS file to just to style something nothing else.
  • finally, index.php is the main file on which everything is to be performed.

crud_applications.sql is just an SQL file which is a database table. The table has this structure and you to create this in your database.

crud-application-in-php-using-jquery-ajax-coding-birds-online-table-structure

Don’t worry, I will provide the SQL file, Source code link is at the end of this post. Please include these CDN in the head tag of your index.php file.

<link rel="shortcut icon" href="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>

and these JavaScript files to the footer means above the body tag in the index.php.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="crud-app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

complete index.php file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CRUD Application in PHP using AJAX - Coding Birds Online</title>
    <link rel="shortcut icon" href="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="custom.css">
</head>
<body>
<div style="margin-top: 10px;"><img width="100" src="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png" class="center-block"/></div>
<div class="container">
    <h3>Delete multiple records from database using PHP </h3>
    <a href="javaScript:void(0);" data-toggle="modal" data-target="#myModal" class="btn btn-primary pull-right bottom-gap">Add New <i class="fa fa-plus" aria-hidden="true"></i></a>
    <table class="table table-bordered">
        <thead id="thead" style="background-color:#135361">
            <tr>
                <th>Sr.No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Contact</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="crudData"></tbody>
    </table>
</div>
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">CRUD Application Form</h4>
            </div>
            <div class="modal-body">
                <form id="crudAppForm">
                   <div class="row">
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="name">Name <span class="field-required">*</span></label>
                               <input type="text" name="name" id="name" placeholder="Name" class="form-control">
                           </div>
                       </div>
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="email">Email <span class="field-required">*</span></label>
                               <input type="text" name="email" id="email" placeholder="Email" class="form-control">
                           </div>
                       </div>
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="contact">Contact <span class="field-required">*</span></label>
                               <input type="text" name="contact" id="contact" placeholder="Contact" class="form-control">
                           </div>
                       </div>
                   </div>
                    <div class="row">
                        <div class="col-md-4">
                            <input type="hidden" name="editId" id="editId" value="" />
                            <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-primary"><i class="fa fa-spinner fa-spin" id="spinnerLoader" ></i> <span id="buttonLabel">Save</span> </button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="crud-app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>

crud-app.js file

$( document ).ready(function() {
    getAllData();
    console.log( "ready!" );
});
$("form#crudAppForm").on("submit",function (e) {
    e.preventDefault();
    var name = $("#name").val();
    var email = $("#email").val();
    var contact = $("#contact").val();
    var editId = $("#editId").val();
    if (name == ""){
        alert("Please enter name");
        $("#name").focus();
    }else if (email == "") {
        alert("Please enter email");
        $("#email").focus();
    }else if (contact == "") {
        alert("Please enter contact");
        $("#contact").focus();
    }else{
        $("#buttonLabel").html("Saving...");
        $("#spinnerLoader").show('fast');
        $.post("crud-script.php",{
            crudOperation:"saveData",
            name:name,
            email:email,
            contact:contact,
            editId:editId,
        },function (response) {
            if (response == "saved") {
                $("#buttonLabel").html("Save");
                $("#spinnerLoader").hide('fast');
                $("#myModal").modal('hide');
                $("form#crudAppForm").each(function () {
                    this.reset();
                });
                getAllData();
            }
        });
    }
});

function getAllData() {
    $.post("crud-script.php",{crudOperation:"getData"},function (allData) {
        $("#crudData").html(allData);
    });
}

function editData(editId,name,email,contact) {
    $("#editId").val(editId);
    $("#name").val(name);
    $("#email").val(email);
    $("#contact").val(contact);
    $("#myModal").modal('show');
}

function deleteData(deleteId) {
    if(confirm("Are you sure to delete this ?")){
        $('#deleteSpinner'+deleteId).show('fast');
        $.post("crud-script.php",{crudOperation:"deleteData",deleteId:deleteId},function (response) {
            if (response == "deleted") {
                $('#deleteSpinner'+deleteId).hide('fast');
                getAllData();
            }
        });
    }
}

crud-script.php file

<?php
include "config.php";
include_once "CrudOperations.php";
$crudObj = new CrudOperations();
if ($_POST['crudOperation'] == "saveData") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $contact = $_POST['contact'];
    $editId = $_POST['editId'];
    $save = $crudObj->saveData($connection,$name,$email,$contact,$editId);
    if ($save){
        echo "saved";
    }
}

if ($_POST['crudOperation'] == "getData") {
    $sr = 1;
    $tableData = '';
    $allData = $crudObj->getAllData($connection);
    if ($allData->num_rows>0) {
        while ($row = $allData->fetch_object()) {
            $tableData .= ' <tr>
                <td>'.$sr.'</td>
                <td>'.$row->name.'</td>
                <td>'.$row->email.'</td>
                <td>'.$row->contact.'</td>
                <td><a href="javaScript:void(0)" onclick="editData(\''.$row->id.'\',\''.$row->name.'\',\''.$row->email.'\',\''.$row->contact.'\');" class="btn btn-success btn-sm">Edit <i class="fa fa-pencil-square-o"></i></a>
                <a href="javaScript:void(0)" onclick="deleteData(\''.$row->id.'\');" class="btn btn-danger btn-sm">Delete <i class="fa fa-trash-o"></i></a>
                <i class="fa fa-spinner fa-spin" id="deleteSpinner'.$row->id.'" style="color: #ff195a;display: none"></i></td>
            </tr>';
            $sr++;
        }
    }
    echo $tableData;
}

if ($_POST['crudOperation'] == "deleteData"){
    $deleteId = $_POST['deleteId'];
    $delete = $crudObj->deleteData($connection,$deleteId);
    if ($delete){
        echo "deleted";
    }
}

config.php file

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

CrudOperations.php file

<?php
class CrudOperations
{
    public function saveData($connection,$name,$email,$contact,$editId)
    {
        if ($editId == "") {
            $query = "INSERT INTO crud_application SET name='$name',email='$email',contact='$contact'";
        }else{
            $query = "UPDATE crud_application SET name='$name',email='$email',contact='$contact' WHERE id='$editId'";
        }
        $result = $connection->query($query) or die("Error in saving data".$connection->error);
        return $result;
    }

    public function getAllData($connection)
    {
        $query = "SELECT * FROM crud_application";
        $result = $connection->query($query) or die("Error in getting data".$connection->error);
        return $result;
    }

    public function deleteData($connection,$deleteId){
        $query = "DELETE FROM crud_application WHERE id='$deleteId'";
        $result = $connection->query($query) or die("Error in deleting data".$connection->error);
        return $result;
    }
}

custom.css

#thead>tr>th{ color: white; }
.center-block {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
.bottom-gap{
    margin-bottom: 10px;
}

.field-required,.delete-spinner{
    color: red;
}
#spinnerLoader{
    display: none;
}

Run the Code!

Now if you run the code, if there are not any errors you will get something like this.

crud-application-in-php-using-jquery-ajax-coding-birds-online-crud-applications-demo

When you will submit this form you will the complete final output like this. And if you click on the Add New+ button this popup form will have appeared.

crud-application-in-php-using-jquery-ajax-coding-birds-online-crud-add-data-example

If you submit this form filling the asked values then the record will be displayed. And to inform you, everything will be on the same page without any reload. Again if you click on the edit button then the same bootstrap popup will appear with the values which you filled previously.

If you update the values then it will call ajax request, update them to the database and display again to the table.

So if you want to delete you can do it also. It will ask you “Are you sure to delete this ?”. If you confirm this then it will be deleted.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Most of the time of want to download the desired folder from GitHub repository but not complete repo. So this post is for you if you are looking for the same. In this article, you will learn how to clone a specific folder from a git.

You will be happy to know that this article is not going to be Technical any more. You just need to copy the path of the file/folder of the repository from GitHub and paste it to the input box and click the download button that’s it.

So without wasting much time lets come into the steps to follow.

  • Head over to Google Search Box and type downgit.
  • Click on the first link. You can directly go to this website.
  • Now copy the path of a specific file/folder from the git repository.
  • And paste this path to the input box and hit the download button.
  • You will get a zip file in return.
  • That’s it !!!

If you have checked this article on searchable select dropdown with country flag. Then you might want to download all the flags of countries that are in the folder of a GitHub repository.

So the complete path is: https://github.com/codingbirdsonline/codingbirds_/tree/master/how-to-make-searchable-select-dropdown/flags

When you will open that website, copy this path and paste it the box looking like this. So this is website looks like you are looking for, how to clone a specific folder from a git.

how-to-clone-a-specific-folder-from-a-git-repository-website-coding-birds-online

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Scrolling a big list of countries, states or cities is annoying sometimes when you are filling a form asking your country to select. Today I come up with a solution to make a searchable drop-down list, very happy to share it with you :).

Today in this tutorial I will tell you how to make a searchable drop-down list in HTML, CSS. You can create a static dropdown but I am creating it to dynamic. Check this demo.

Problem

As you know the problem, that’s why you are here for the solution. LOL…, So the problem is this, suppose you have created a form in your website or web application, you have a long dropdown list to select it as you might have seen on a variety of websites. You need to scroll it until you did not find the item you are looking for.

coding-birds-online-how-to-make-a-searchable-drop-down-list-problem

Solution

The solution is select2. Select2 is a jQuery based replacement for select boxes. It supports searching remote data sets and infinite scrolling of results.

When you will integrate this, you will get a search box at the top of the select dropdown list. Now you can search the item you are looking for in a long list. You can check the installation guide also on the official website.

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>

Import these CDN links to the head of the HTML page and paste this shortcode to the footer to make your dropdown list searchable.

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $('.your-select-dropdown-class').select2();
});

Don’t worry I will show you how to code step by step. I am creating this select 2 dropdown list dynamic by fetching the countries from the database. Let’s check the folder structure.

Addidtionally, I will show country flags in the dropdown, to make it more beautifull and eye catchy to the users.

coding-birds-online-how-to-make-a-searchable-drop-down-list-folder-structure

Step by step to code

  • Create an index.php file to show the select dropdown list.
  • config.php is the connection file to the database.
  • flags folder contains all the flags of the countries. I will provide it.

Now create these files.

index.php complete code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>
    <title>How to make searchable dropdown with country flag - Coding Birds Online</title>
    <style>.required{color: #FF0000;}
           .flag{background-color: #ff884b;padding: 10px;border-radius: 20px;color: white}
    </style>
</head>
<body>
<div class="container">
    <?php
    include "config.php";
    $query = "SELECT * FROM bird_searchable_dropdown";
    $countries = $connection->query($query);
    ?>
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center><img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"></center>
                    <h5 class="card-title text-center">Searchable dropdown with country <span class="flag">FLAG</span></h5>
                    <form>
                        <div class="form-label-group">
                            <label for="inputEmail">Country <span class="required">*</span></label>
                            <select  name="select2" id="select2" class="form-control">
                                <option value="">Select</option>
                                <?php
                                if ($countries->num_rows>0){
                                    while ($country = $countries->fetch_object()){ ?>
                                        <option value="<?php echo $country->code;?>"><?php echo $country->countryname;?></option>
                                   <?php  }
                                }
                                ?>
                            </select>
                        </div> <br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#select2").select2({
        templateResult: formatState
    });
    function formatState (state) {
        if (!state.id) {
            return state.text;
        }
        var baseUrl = "flags";
        var $state = $(
            '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
        );
        return $state;
    }
</script>
</body>
</html>

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code to get the searchable drop-down list

When you run the code you will get this output as I told above in the solution.

coding-birds-online-how-to-make-a-searchable-drop-down-list-final-output

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here

Check this https://minhaskamal.github.io/DownGit/ link to download a single folder(flags folder) from a repository on GitHub.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂