Thursday, 21 October 2021

PHP Project | How to Create eCommerce Product Filter with Pagination using Vanilla JavaScript


How to Add Multiple Search Filter in PHP with pagination for eCommerce Website Products filters using pure Vanilla JavaScript. If you are also looking for How can we implement search filters with pagination in eCommerce website then you have come on the right place because here we have share PHP Project tutorial on How to Create filter in PHP with MySQL, JavaScript and Bootstrap 5 library. Under this tutorial, we have latest web technology like Vanilla JavaScript and Bootstrap 5 library for build eCommerce website product filter with pagination.

Now we have come on the right topic and here we will show you how to filter product which has been come under price range, brand or gender filter. The main benefits of eCommerce Website product filter is for filter product from large number of product by price range filter, brand filter or gender filter. So most of the Online eCommerce website has put product filter on their website and with the help of that filter customer product from large number of product and found the specific product within their price range or brands. If you have seen any Online Shopping website, so on that website there are large number of product has been listed on that website, so when we have come on e-commerce website for buy product then we have to face difficulty for find product, so at that time product filter will help to user for search product on website and it has reduces user time for found product with the help of price range filter or brand filter.

PHP Project | How to Create eCommerce Product Filter with Pagination using Vanilla JavaScript

In this post you, we will learn you how to filter product on eCommerce website using PHP with pure JavaScript, Bootstrap 5 and MySQL. If you have build Product filter for Online Shopping website then good User interface (UI) is required for product filter so customer can easily search product with multiple filter. Under this tutorial, we will use Radio Button filter, Price Range filter and Checkbox filter using JavaScript. When user click on Radio Button or price filter or Checkbox filter then JavaScript will trigger fetch API and it will fetch data from MySQL database and display on web page without refresh of web page. So here for Ajax operation we have use JavaScript Fetch API. Under this tutorial we will put multiple search filter at the left sidebar, and here we have will make brand filter using radio button, price range filter and brand filter using checkbox. This is live product filter which has been run based on JavaScript Fetch API Ajax request and most of the e-commerce website use Ajax for search filter. Below you can find the source code which will help you to build product filter with multiple search filter and pagination for you ecommerce website project using PHP with JavaScript, Bootstrap 5 and MySQL Database.






Source Code


Create MySQL Table


For build product filter, first we have to create MySQL table for store product data. So for create table in MySQL database, you have to run following SQL script which will create sample_data table in your MySQL Database.


--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `sample_id` int(11) NOT NULL,
  `name` text NOT NULL,
  `sku` int(11) NOT NULL,
  `mpn` int(11) NOT NULL,
  `price` int(11) NOT NULL,
  `in_stock` varchar(20) NOT NULL,
  `currency` varchar(10) NOT NULL,
  `brand` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `images` text NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`sample_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `sample_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.html


Under this tutorial, we have use pure JavaScript for create product filter with pagination. So here we have use .html file as our index file. Under this file we have only include Bootstrap 5 Stylesheet library for create layout for product filter and for pagination. Under this file you can also find JavaScript code for display all product with pagination link.

For display all product with pagination, here we have create one load_product(page) function. This function will be called when page has been load in browser, then it will send AJAX request using JavaScript Fetch API to process.php file for fetch product data from database. So this function will receive product data with pagination link data from server in JSON format and convert that data into HTML format and display all product with pagination link on web page.

Under this Product Filter tutorial, we have also add Skeleton Loading Effect with Bootstrap 5 stylesheet and JavaScript. So when page will load it will first load Product Skeleton and then after it will display product on web page with pagination link. Here skeleton effect will also work when we have click on pagination link also.


<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <meta name="generator" content="">
        <title>Product Filter in PHP using Vanilla JavaScript</title>

        <link rel="canonical" href="">

        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


        <style>
          .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            user-select: none;
          }

          @media (min-width: 768px) {
            .bd-placeholder-img-lg {
              font-size: 3.5rem;
            }
          }

        </style>
    </head>
  
    <body>
    
        <div class="col-lg-8 mx-auto">

            <main>
                <h1 class="text-center mt-3 mb-3">Product Filter in PHP using Vanilla JavaScript - Add Skeleton Loading Effect - 3</h1>

                <div class="row">

                    <div class="col-sm-3 p-3 bg-light"></div>

                    <div class="col-sm-9">
                        <div id="product_area"></div>

                        <div id="skeleton_area"></div>

                        <div id="pagination_area" class="mt-2 mb-5"></div>
                    </div>

                </div>
                
                
            </main>
        </div>

    </body>
</html>

<script>

function $(selector){

    return document.querySelector(selector);

}

load_product(1);

function load_product(page = 1)
{
    $('#product_area').style.display = 'none';

    $('#skeleton_area').style.display = 'block';

    $('#skeleton_area').innerHTML = make_skeleton();

    fetch('process.php?page='+page+'').then(function(response){

        return response.json();

    }).then(function(responseData){

        var html = '';

        if(responseData.data)
        {
            if(responseData.data.length > 0)
            {
                html += '<p class="h6">'+responseData.total_data+' Products Found</p>';

                html += '<div class="row">';

                for(var i = 0; i < responseData.data.length; i++)
                {
                    html += '<div class="col-md-3 mb-2 p-3">';

                    html += '<img src ="'+responseData.data[i].image+'" class="img-fluid border mb-3 p-3" />';

                    html += '<p class="fs-6 text-center">'+responseData.data[i].name+'&nbsp;&nbsp;&nbsp;<span class="badge bg-info text-dark">'+responseData.data[i].brand+'</span><br />';

                    html += '<span class="fw-bold text-danger"><span>&#8377;</span> '+responseData.data[i].price+'</span>';

                    html += '</div>';
                }

                html += '</div>';

                $('#product_area').innerHTML = html;
            }
            else
            {
                $('#product_area').innerHTML = '<p class="h6">No Product Found</p>';
            }
        }

        if(responseData.pagination)
        {
            $('#pagination_area').innerHTML = responseData.pagination;
        }

        setTimeout(function(){

            $('#product_area').style.display = 'block';

            $('#skeleton_area').style.display = 'none';

        }, 3000);

    });
}

function make_skeleton()
{
    var output = '<div class="row">';

    for(var count = 0; count < 8; count++)
    {
        output += '<div class="col-md-3 mb-3 p-4">';

        output += '<div class="mb-2 bg-light text-dark" style="height:240px;"></div>';

        output += '<div class="mb-2 bg-light text-dark" style="height:50px;"></div>';

        output += '<div class="mb-2 bg-light text-dark" style="height:25px;"></div>';

        output += '</div>';
    }

    output += '</div>';

    return output;
}

</script>


process.php


This file has been use for perform server side operation. Under this file we have use PHP script for process server side data. In this file first we have make database connection using PHP PDO() class.

This file has been receive Ajax request for fetch product data from database and make pagination link. So based on $page number variable value which has been get from url and based on that value it has been fetch product data from database for display particular page product on web page.


<?php

//process.php

$connect = new PDO("mysql:host=localhost; dbname=test", "root", "");

if(isset($_GET["page"]))
{
	$data = array();

	$limit = 8;

	$page = 1;

	if($_GET["page"] > 1)
	{
		$start = (($_GET["page"] - 1) * $limit);

		$page = $_GET["page"];
	}
	else
	{
		$start = 0;
	}

	$query = "
	SELECT name, price, images, brand 
	FROM sample_data 
	ORDER BY sample_id ASC
	";

	$filter_query = $query . ' LIMIT ' . $start . ', ' . $limit . '';

	$statement = $connect->prepare($query);

	$statement->execute();

	$total_data = $statement->rowCount();

	$result = $connect->query($filter_query);

	foreach($result as $row)
	{
		$image_array = explode(" ~ ", $row["images"]);

		$data[] = array(
			'name'		=>	$row['name'],
			'price'		=>	$row['price'],
			'brand'		=>	$row['brand'],
			'image'		=>	$image_array[0]
		);
	}

	$pagination_html = '
	<nav aria-label="Page navigation example">
  		<ul class="pagination justify-content-center">
	';

	$total_links = ceil($total_data/$limit);

	$previous_link = '';

	$next_link = '';

	$page_link = '';

	$page_array = '';

	if($total_links > 4)
	{
		if($page < 5)
		{
			for($count = 1; $count <= 5; $count++)
			{
				$page_array[] = $count;
			}

			$page_array[] = '...';

			$page_array[] = $total_links;
		}
		else
		{
			$end_limit = $total_links - 5;

			if($page > $end_limit)
			{
				$page_array[] = 1;

				$page_array[] = '...';

				for($count = $end_limit; $count <= $total_links; $count++)
				{
					$page_array[] = $count;
				}
			}
			else
			{
				$page_array[] = 1;

				$page_array[] = '...';

				for($count = $page - 1; $count <= $page + 1; $count++)
				{
					$page_array[] = $count;
				}

				$page_array[] = '...';

				$page_array[] = $total_links;
			}
		}
	}
	else
	{
		for($count = 1; $count <= $total_links; $count++)
		{
			$page_array[] = $count;
		}
	}

	for($count = 0; $count < count($page_array); $count++)
	{
		if($page == $page_array[$count])
		{
			$page_link .= '
				<li class="page-item active">
		      		<a class="page-link" href="#">'.$page_array[$count].'</a>
		    	</li>
			';

			$previous_id = $page_array[$count] - 1;

			if($previous_id > 0)
			{
				$previous_link = '<li class="page-item"><a class="page-link" href="javascript:load_product('.$previous_id.')">Previous</a></li>';
			}
			else
			{
				$previous_link = '
					<li class="page-item disabled">
				        <a class="page-link" href="#">Previous</a>
				    </li>
				';
			}

			$next_id = $page_array[$count] + 1;

			if($next_id > $total_links)
			{
				$next_link = '
					<li class="page-item disabled">
		        		<a class="page-link" href="#">Next</a>
		      		</li>
				';
			}
			else
			{
				$next_link = '
				<li class="page-item"><a class="page-link" href="javascript:load_product('.$next_id.')">Next</a></li>
				';
			}
		}
		else
		{
			if($page_array[$count] == '...')
			{
				$page_link .= '
					<li class="page-item disabled">
		          		<a class="page-link" href="#">...</a>
		      		</li>
				';
			}
			else
			{
				$page_link .= '
					<li class="page-item">
						<a class="page-link" href="javascript:load_product('.$page_array[$count].')">'.$page_array[$count].'</a>
					</li>
				';
			}
		}
	}

	$pagination_html .= $previous_link . $page_link . $next_link;


	$pagination_html .= '
		</ul>
	</nav>
	';

	$output = array(
		'data'		=>	$data,
		'pagination'=>	$pagination_html,
		'total_data'=>	$total_data
	);

	echo json_encode($output);
}

?>



Sunday, 10 October 2021

PHP Project on Real Time Chat Application using Vanilla JavaScript


This is a fully functional web based PHP & Vanilla JavaScript Chat Application project on Real Time Chat application which has been build with PHP script, MySQL Database, Vanilla JavaScript and Bootstrap 5 library. Under this PHP an Vanilla JavaScript Project, it has cover all essential functionality or features which you can use under your second year or final year student for their collage projects. This PHP Chat Application has many number of features like multiple user can chat with each other in real-time. This system is a Single page Chat application in which all operation like search user, accept chat request, real time chat with each other and profile setting. This all operation user can do on same page without going to other page without refresh of web page. By follow this tutorial, you can learn how to create Chat Web Application using PHP with MySQL and Vanilla JavaScript.

About Realtime Chat App using PHP & Vanilla JavaScript


This Chat Application in PHP and JavaScript, we have mainly focuses on how user can chat in real-time using Vanilla JavaScript. Because we have already published Chat application tutorial using jQuery but there are many viewers has requested us to published how to make chat application in PHP using JavaScript because for JavaScript can be run independently but for run jQuery we have to load jQuery library first. So many programmers are prefer Vanilla JavaScript for their web development project. So for here also we have use Vanilla JavaScript for build Real time chat application project. Under this Chat Application, we have use Vanilla JavaScript Fetch API for make real-time chat application.


PHP Project on Real Time Chat Application using Vanilla JavaScript


Feature of Chat Application


  • User Registration
  • User Login
  • User Setting Page
  • Search other User of this Chat System
  • Send Chat Request
  • Load Chat Request in Notification
  • Accept Chat Request
  • Realtime Chatting

Technology Used in Chat Application


Server-side

  • PHP
  • MySQL Database

Client-side


  • Vanilla JavaScript
  • JavaScript Fetch API
  • Bootstrap 5




How to Get Chat Application Source Code


  1. Below you can find Demo link, so click on that Chat application Demo Link.
  2. Once Chat Application Demo has been open first you have to register under this Chat Application.
  3. Once you have register under this PHP Chat Application Demo, then you will received email verification email, so you have to verify your email address.
  4. After Email verification, you will be redirect to index.html page and on that page you can fine chat application login area. So their you have to enter your login details.
  5. After Login in to Chat Application demo, now you will be login under this chat application and with setting button, you can find source code download link.
  6. Once you have click on Chat Application Source Code download link, then source code will download in you local computer.
  7. Once source code has been downloaded you will be redirect again this Chat Application post, and on this post you can find password link, so once you have click on that link you will be redirect to YouTube video, and under that video description, you can find password for source code file, because source code file is password protected. So this is complete process of how to get Chat Application Source Code.

How to Run Chat Application?


  1. After Source code file and password of Source Code file, then you have to unzip the project file under this directory of XAMPP.
  2. Under XAMPP directory you will find folder naming "htdocs"
  3. Under the "htdocs" directory, you have to unzip PHP Chat Application Source code.
  4. Next you have to open your browser like Google chrome or Mozilla Firefox.
  5. Under Browser you have to go URL like "http://localhost/phpmyadmin".
  6. Under PHPMyAdmin you have to first create database and after create database, you have to create table for chat application. Under source code you can file chat.sql file for create required table for this chat system.
  7. After create table in database, you have to open [project_folder_name]/backend/Db.php file.
  8. Under this file, you have to define database name and base url of your chat application and save that file.
  9. Once you have setting all above these, now you have to go to url "http://localhost/[ PROJECT_FOLDER_NAME ]/"
  10. For check chat application, first you have to register under that system and then after you have to login under that system and check chat application.

So This is real time Chat Application in PHP with Vanilla JavaSCript project, which will helpful to both immediate level programmer and senior level programmer who want to work with PHP script and Vanilla JavaScript and want to build robust application with this technology. And at lastly, here we have share complete source code of PHP and Vanilla JavaScript Chat Application, so download it and learn something new from that source code and build another level Chat Application.







Sunday, 26 September 2021

PHP MySQL Project on Medical Store Management System


This is PHP and MySQL Project on Medical Store or Shop Management System and this Pharmacy Management System is a web based PHP Project and it has been developed in PHP Language and MySQL database. With the help of this free pharmacy management system, we can manage medicine location details, medicine company data, medicine supplier data, live medicine inventory data, medicine purchase and sales data and even we can also create medicine sales bill also. The main object for develop Online Medical Store Management System with PHP and MySQL for overcome the manual errors in operate Medical store and convert whole Medical Store day to day work like managing sells, medicine purchase, medicine stock or inventory, medicine billing into computerized system.

This Medical Store Management System is web based application, so multiple user can work on the system at the same time. This is nice project for your education purpose. If you want to learn How to build web application in PHP step by step, then this is best PHP Project in which you can learn lots of things regarding how to build big web application in PHP. In this Medical Shop Management System Project there are many modules like Medicine Category module, Location Rack module, medicine company module, medicine supplier module, medicine purchase module, medicine module and medicine module. By using this project User can easily manage the inventory of their medical store easily and generate medical sales bill also. Their whole medical store data will store in centralized system. So from one location they can easily track the total sales, total purchase data, in stock medicine data and out of stock medicine data in single click.


PHP MySQL Project on Medical Store Management System


Technology of User for Build Medical Store Management System


Server Side


  • PHP
  • MySQL
  • DomPDF Library

Client Side


  • Vanilla JavaScript
  • Bootstrap 5
  • Vanilla JavaScript Simple-DataTables
  • Font Awesome Library
  • Vanilla SelectBox
  • Chart.js

Users of Medical Store Management System


Under this Online Pharmacy Billing System, there are main two user.

  • Admin or Master User
  • Sub User will be created by Master User

Relational Model Diagram of Medical Store Management System


PHP Project on Medical Store Management System

Modules of Medical Store Management System


This are the main modules of this PHP and MySQL Pharmacy Management System.

  1. Medicine Category Module : Master User can Add, Edit, Read and Delete Medicine Category data under this Category Module.
  2. Medicine Location Rack Module : Master User can Add, Edit, Read and Delete Medicine Location Rack data under this Location Rack Module.
  3. Medicine Company Module : Master User can Add, Edit, Read and Delete Medicine Company data under this Company Module.
  4. Medicine Supplier Module : Master User can Add, Edit, Read and Delete Medicine Supplier data under this Medicine Supplier Module.
  5. Medicine Module : Master User can Add, Edit, Read and Delete Medicine data under this Medicine Module.
  6. Medicine Purchase Module : Master User or Sub User can Add, Edit, Read and Delete Medicine Purchase data under this Medicine Purchase Module.
  7. Medicine Sells Module : Master User or Sub User can Add, Edit, Read and Delete Medicine Sells data and they can also generate Medicine Sells Bill also under this Medicine Sells Module.
  8. System Set Up Module : When first time this system has been run then this set up module will create database connection under this system, then after it will make required Mysql table under define database, next it will create master or admin user account and at the end of set up it will also set up medical store also.
  9. Login Module : With help of this Login module, Master User or Sub User can get access into under Medical Store Management System.
  10. User Module : Master User can Add, Edit, Read and Delete Sub User data under this User Module.
  11. Analytics Module : Master can see analytics data like No. of In Stock Medicine, No. of Out of Stock Medicine, Total value of Sales, Total Values of Purchase, Master user can see last 15 days sales data in graph format. In this Analytics Master user can see last six month Medicine store data in graph format and at the end of page, Master user can see the list of out of Stock Medicine.




Run Medical Store Management System in Local Computer or Laptop


  • Download XAMPP Server and Install in your Computer.
  • After Install XAMPP Server, Start Apache and MySQL Server in installed XAMPP Server.
  • Next you can download source code file from this web page, we have put source code download link at below of this web page.
  • When you have click on below source code download link, then it will redirect to another page, and on that page you have to enter your email address.
  • Once you have enter your email address, then source code download link will be send to your email address. If you have not received email in your Inbox, please check your SPAM folder.
  • Once you have download Medical Store Management System Source code, so you have to extract source code file under xampp/htdocs folder where you have install xampp server.
  • This Pharmacy Stop Management System Source is password protected, so you can get source code file at this the Video description.
  • Once you have extract file in xampp/htdocs folder, then after you have to open browser and visit localhost/phpmyadmin. And create new blank database for this Medical Store Management System.
  • After this in another tab, you have to run http://localhost/msbs/index.php file of this Pharmacy Management System.
  • When you have hit above URL then it will first you ask Mysql database configuration details and base url details. So when you fill required details, and submit format, then it will make database connection and create required folder in define MySQL database.
  • After this it will ask you Master user registration details like email address, name and password details, once you have fill all details and submit form then it will create master user account under this Medical Store Management System.
  • Once Master user account has been created then it will ask for set up medical store details, so in this step you have to define medical store details and once you have fill all details and submit it, it will create medical store under this PHP Pharmacy Management and Billing System.
  • After follow all above step lastly it will redirect you to login page so here you have to enter master user login details. So follow this step and run this Medical Store Management System.

This is fully dynamic Medical Store Management System which has been build in PHP language with MySQL Database, and here you can get the complete source code of Medical Shop Management System, so you can run this system in your localhost and check the functionality of this system and you can learn how to build any system in PHP.

If you have find any bug under this system, please share under comment box, we will overcome that bug and we will again published error free source code of this Medical Store Management System.

If you have any suggestion or we have to required to add any feature under this Medical Shop Management system, please write your suggestion under this post comment box, we will add you suggestion under this system and we will again published updated source code of Pharmacy Shop and Billing System.







Saturday, 14 August 2021

Live Vanilla DataTables CRUD with JavaScript PHP & MySql

Vanilla DataTables is a JavaScript library which is write in pure Vanilla JavaScript and it used for load dynamic MySql table data in a very interactive and user friendly way. This Vanilla DataTables have very rich features which you allows to perform live searching, sorting and server-side processing of data.

So if you are looking for implementing Vanilla DataTables in your web application, then you have first learn the basic How can we perform CRUD (Create, Read, Update, Delete) operation with this Vanilla DataTables. If you want to learn Basic CRUD opeation with Vanilla DataTables, then you have come on the right place. Because in previous tutorial we have already show you how to load dynamic MySql table data under this Vanilla DataTables with server-side processing of Data using PHP script. Now in this tutorial, we will show you how to implement Live CRUD operation with Vanilla DataTables by using JavaScript fetch API, Ajax PHP and Mysql Database.

In this tutorial, we will cover how to perform CRUD operation with Vanilla DataTables step by step. So here we will create Vanilla DataTables single page CRUD application with Mysql table dynamic Data.

So now lets create how to make Live Vanilla DataTables CRUD Application with JavaScript, Ajax, PHP and Mysql. Below you can find the file structure of Vanilla DataTables CRUD Application.

  • action.php
  • fetch.php
  • function.php
  • index.php

Live Vanilla DataTables CRUD with JavaScript PHP & MySql






Step 1: Create MySQL Database Table


For Perform CRUD Operation with Vanilla DataTables, so first we need to create Mysql database table, so we have to run following SQL script for create customer_table for CRUD operation.


--
-- Database: `testing`
--

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

--
-- Table structure for table `customer_table`
--

CREATE TABLE `customer_table` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(200) NOT NULL,
  `customer_last_name` varchar(200) NOT NULL,
  `customer_email` varchar(300) NOT NULL,
  `customer_gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customer_table`
--
ALTER TABLE `customer_table`
  ADD PRIMARY KEY (`customer_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customer_table`
--
ALTER TABLE `customer_table`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT;





Step 2: Include Bootstrap Stylesheet, JSTable Library


In this tutorial we have use pure JavaScript, so here we will only use Bootstrap stylesheet library and for Vanilla DataTables here we have use JSTable library which is written in pure JavaScript. This files, we have to include in index.php file.


         <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="library/jstable.css" />

        <script src="library/jstable.min.js" type="text/javascript"></script>


Step 3: Load Data in Vanilla DataTable with Server-side Processing


In CRUD Application first stage we need to load dynamic data in Vanilla DataTables with Server side processing of Data. So first we have to create one html table in index.php file.


<span id="success_message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-md-6">Customer Data</div>
                        <div class="col col-md-6" align="right">
                            <button type="button" name="add_data" id="add_data" class="btn btn-success btn-sm">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="customer_table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php echo fetch_top_five_data($connect); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>


After this, we have load data under this DataTables when page has been load, So we have to write php script for last five data and count total number of data under this mysql table. So we have to open function.php and write PHP script under this file.


<?php

//function.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");



function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5";

	$result = $connect->query($query);

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
		</tr>
		';
	}
	return $output;
}

function count_all_data($connect)
{
	$query = "SELECT * FROM customer_table";

	$statement = $connect->prepare($query);

	$statement->execute();

	return $statement->rowCount();
}

?>


After this we have to called PHP fetch_top_five_data($connect) function at index.php file, so when page load then it will display last five data in Vanilla DataTable.

Next we have go to index.php file and we need to initialize Vanilla DataTables. So for this, we have to write following script in JavaScript section.


var table = new JSTable("#customer_table", {
    serverSide : true,
    deferLoading : <?php echo count_all_data($connect); ?>,
    ajax : "fetch.php"
});


This script will send Ajax request to fetch.php file and by this script we can perform server-side processing of data and perform searching, sorting and pagination operation at server-side. Below you can find fetch.php source in which you can learn how to write php script for perform server-side processing of data.


<?php

//fetch.php

include('function.php');

$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);

$start = $startGET ? intval($startGET) : 0;

$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);

$length = $lengthGET ? intval($lengthGET) : 10;

$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);

$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
	';


if($sortColumnIndex != '')
{
	$query .= 'ORDER BY '.$column[$sortColumnIndex].' '.$sortDirection.' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

$statement = $connect->prepare($query);

$statement->execute();

$number_filter_row = $statement->rowCount();

$result = $connect->query($query . $query1);

$data = array();

foreach($result as $row)
{
	$sub_array = array();

	$sub_array[] = $row['customer_first_name'];

	$sub_array[] = $row['customer_last_name'];

	$sub_array[] = $row['customer_email'];

	$sub_array[] = $row['customer_gender'];

	$data[] = $sub_array;
}



$output = array(
	"recordsTotal"		=>	count_all_data($connect),
	"recordsFiltered"	=>	$number_filter_row,
	"data"				=>	$data
);

echo json_encode($output);

?>


Step 4: Add or Insert Data into Mysql Table using Bootstrap Modal


Under this Vanilla DataTables CRUD Application, we will use Bootstrap Modal for process data for Add or Insert Data into Mysql table using JavaScript Fetch API with PHP Script. So first we need to create Bootstrap Modal in index.php file.


<div class="modal" id="customer_modal" tabindex="-1">
    <form method="post" id="customer_form">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h5 class="modal-title" id="modal_title">Add Customer</h5>

                    <button type="button" class="btn-close" id="close_modal" data-bs-dismiss="modal" aria-label="Close"></button>

                </div>

                <div class="modal-body">

                    <div class="mb-3">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" />
                        <span class="text-danger" id="first_name_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" />
                        <span class="text-danger" id="last_name_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="text" name="customer_email" id="customer_email" class="form-control" />
                        <span class="text-danger" id="customer_email_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select name="customer_gender" id="customer_gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>

                </div>

                <div class="modal-footer">
                    <input type="hidden" name="action" id="action" value="Add" />
                    <button type="button" class="btn btn-primary" id="action_button">Add</button>
                </div>

            </div>

        </div>

    </form>

</div>

<div class="modal-backdrop fade show" id="modal_backdrop" style="display:none;"></div>


Under this tutorial, we will pop up and close Bootstrap Modal by using JavaScript without using jQuery library and after pop up Bootstrap Modal we need to send form data from Modal to PHP Script, so for this we will use JavaScript Fetch API, so this code you can find below which has been write in index.php file.


function _(element)
{
    return document.getElementById(element);
}

function open_modal()
{
    _('modal_backdrop').style.display = 'block';
    _('customer_modal').style.display = 'block';
    _('customer_modal').classList.add('show');
}

function close_modal()
{
    _('modal_backdrop').style.display = 'none';
    _('customer_modal').style.display = 'none';
    _('customer_modal').classList.remove('show');
}

_('add_data').onclick = function(){
    open_modal();
}

_('close_modal').onclick = function(){
    close_modal();
}

_('action_button').onclick = function(){

    var form_data = new FormData(_('customer_form'));

    _('action_button').disabled = true;

    fetch('action.php', {

        method:"POST",

        body:form_data

    }).then(function(response){

        return response.json();

    }).then(function(responseData){

        _('action_button').disabled = false;

        if(responseData.success)
        {
            _('success_message').innerHTML = responseData.success;

            close_modal();

            table.update();
        }
        else
        {
            if(responseData.first_name_error)
            {
                _('first_name_error').innerHTML = responseData.first_name_error;
            }
            else
            {
                _('first_name_error').innerHTML = '';
            }

            if(responseData.last_name_error)
            {
                _('last_name_error').innerHTML = responseData.last_name_error;
            }
            else
            {
                _('last_name_error').innerHTML = '';
            }

            if(responseData.customer_email_error)
            {
                _('customer_email_error').innerHTML = responseData.customer_email_error;
            }
            else
            {
                _('customer_email_error').innerHTML = '';
            }
        }

    });

}


Now at server side data will be received at action.php file. This file will first check validation error, if there is validation error occures then it will send validation error to index.php which will display under Bootstrap Modal and suppose data are proper then it will Insert or Add into Mysql table using PHP script.


<?php

//action.php

include('function.php');

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'Add' || $_POST["action"] == 'Update')
	{
		$output = array();
		$first_name = $_POST["first_name"];
		$last_name = $_POST["last_name"];
		$customer_email = $_POST["customer_email"];

		$customer_gender = $_POST["customer_gender"];

		if(empty($first_name))
		{
			$output['first_name_error'] = 'First Name is Required';
		}

		if(empty($last_name))
		{
			$output['last_name_error'] = 'Last Name is Required';
		}

		if(empty($customer_email))
		{
			$output['customer_email_error'] = 'Email is Required';
		}
		else
		{
			if(!filter_var($customer_email, FILTER_VALIDATE_EMAIL))
			{
				$output['customer_email_error'] = 'Invalid Email Format';
			}
		}

		if(count($output) > 0)
		{
			echo json_encode($output);
		}
		else
		{
			if($_POST['action'] == 'Add')
			{
				$data = array(
					':customer_first_name'		=>	$first_name,
					':customer_last_name'		=>	$last_name,
					':customer_email'			=>	$customer_email,
					':customer_gender'			=>	$customer_gender
				);	

				$query = "
				INSERT INTO customer_table 
				(customer_first_name, customer_last_name, customer_email, customer_gender) 
				VALUES (:customer_first_name, :customer_last_name, :customer_email, :customer_gender)
				";

				$statement = $connect->prepare($query);

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">New Data Added</div>';

					echo json_encode($output);
				}
			}
		}
	}

}

?>


Step 5: Edit or Update Mysql Data with Bootstrap Modal


Under this Vanilla DataTables CRUD application, we have come one Update Data operation. So for update data operation, we need to fetch singe customer data from database and load in Bootstrap modal, so we can change data in Bootstrap modal and again submit to form for update data operation. So first we need to send Ajax request to for fetch single customer data by using Fetch API, which source code you can find below.

index.php

function fetch_data(id)
{
    var form_data = new FormData();

    form_data.append('id', id);

    form_data.append('action', 'fetch');

    fetch('action.php', {

        method:"POST",

        body:form_data

    }).then(function(response){

        return response.json();

    }).then(function(responseData){

        _('first_name').value = responseData.first_name;

        _('last_name').value = responseData.last_name;

        _('customer_email').value = responseData.customer_email;

        _('customer_gender').value = responseData.customer_gender;

        _('customer_id').value = id;

        _('action').value = 'Update';

        _('modal_title').innerHTML = 'Edit Data';

        _('action_button').innerHTML = 'Edit';

        open_modal();

    });
}


When this above Ajax request will be send then at action.php file, it will fetch single customer data from Mysql database and send back data to ajax request in JSON format.

action.php

if($_POST['action'] == 'fetch')
	{
		$query = "
		SELECT * FROM customer_table 
		WHERE customer_id = '".$_POST["id"]."'
		";

		$result = $connect->query($query);

		$data = array();

		foreach($result as $row)
		{

			$data['first_name'] = $row['customer_first_name'];

			$data['last_name'] = $row['customer_last_name'];

			$data['customer_email'] = $row['customer_email'];

			$data['customer_gender'] = $row['customer_gender'];

		}

		echo json_encode($data);
	}



When above script data to Ajax request, then Bootstrap modal will be pop up with filled customer data and we can edit customer details and again send back data to action.php file, which you can seen below.

action.php

if($_POST["action"] == 'Add' || $_POST["action"] == 'Update')
	{
		$output = array();
		$first_name = $_POST["first_name"];
		$last_name = $_POST["last_name"];
		$customer_email = $_POST["customer_email"];

		$customer_gender = $_POST["customer_gender"];

		if(empty($first_name))
		{
			$output['first_name_error'] = 'First Name is Required';
		}

		if(empty($last_name))
		{
			$output['last_name_error'] = 'Last Name is Required';
		}

		if(empty($customer_email))
		{
			$output['customer_email_error'] = 'Email is Required';
		}
		else
		{
			if(!filter_var($customer_email, FILTER_VALIDATE_EMAIL))
			{
				$output['customer_email_error'] = 'Invalid Email Format';
			}
		}

		if(count($output) > 0)
		{
			echo json_encode($output);
		}
		else
		{
			$data = array(
				':customer_first_name'		=>	$first_name,
				':customer_last_name'		=>	$last_name,
				':customer_email'			=>	$customer_email,
				':customer_gender'			=>	$customer_gender
			);
			
			if($_POST['action'] == 'Add')
			{
				$query = "
				INSERT INTO customer_table 
				(customer_first_name, customer_last_name, customer_email, customer_gender) 
				VALUES (:customer_first_name, :customer_last_name, :customer_email, :customer_gender)
				";

				$statement = $connect->prepare($query);

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">New Data Added</div>';

					echo json_encode($output);
				}
			}

			if($_POST['action'] == 'Update')
			{
				$query = "
				UPDATE customer_table 
				SET customer_first_name = :customer_first_name, 
				customer_last_name = :customer_last_name, 
				customer_email = :customer_email, 
				customer_gender = :customer_gender 
				WHERE customer_id = '".$_POST["customer_id"]."'
				";

				$statement = $connect->prepare($query);

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">Data Updated</div>';
				}

				echo json_encode($output);
			}
		}
	}


Step 6: Delete or Remove Data From Mysql with Fetch API


After performing update data operation with Bootstrap Modal, now we need to remove unwanted data from MySQL table, so in this step we will show you how to delete or remove data fromm MySQL table by using JavaScript Fetch API with PHP script and display remaining data in Vanilla JavaScript DataTables.

For Delete data from Database, first we need to create delete button in each row of table, so we have make required changes in function.php file and fetch.php file. Under this file code, so it will add make delete button in row of data in Vanilla DataTables.

function.php

function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5";

	$result = $connect->query($query);

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
			<td><button type="button" onclick="fetch_data('.$row["customer_id"].')" class="btn btn-warning btn-sm">Edit</button>&nbsp;<button type="button" class="btn btn-danger btn-sm" onclick="delete_data('.$row["customer_id"].')">Delete</button></td>
		</tr>
		';
	}
	return $output;
}



fetch.php

<?php

//fetch.php

include('function.php');

$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);

$start = $startGET ? intval($startGET) : 0;

$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);

$length = $lengthGET ? intval($lengthGET) : 10;

$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);

$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
	';


if($sortColumnIndex != '')
{
	$query .= 'ORDER BY '.$column[$sortColumnIndex].' '.$sortDirection.' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

$statement = $connect->prepare($query);

$statement->execute();

$number_filter_row = $statement->rowCount();

$result = $connect->query($query . $query1);

$data = array();

foreach($result as $row)
{
	$sub_array = array();

	$sub_array[] = $row['customer_first_name'];

	$sub_array[] = $row['customer_last_name'];

	$sub_array[] = $row['customer_email'];

	$sub_array[] = $row['customer_gender'];

	$sub_array[] = '<button type="button" onclick="fetch_data('.$row["customer_id"].')" class="btn btn-warning btn-sm">Edit</button>&nbsp;<button type="button" class="btn btn-danger btn-sm" onclick="delete_data('.$row["customer_id"].')">Delete</button>';

	$data[] = $sub_array;
}



$output = array(
	"recordsTotal"		=>	count_all_data($connect),
	"recordsFiltered"	=>	$number_filter_row,
	"data"				=>	$data
);

echo json_encode($output);

?>


So when user click on delete button then it will called delete_data(id) javascript function which will send ajax request to PHP script using JavaScript Fetch API, this function we have to make in index.php file.

index.php

function delete_data(id)
{
    if(confirm("Are you sure you want to remove it?"))
    {
        var form_data = new FormData();

        form_data.append('id', id);

        form_data.append('action', 'delete');

        fetch('action.php', {

            method:"POST",

            body:form_data

        }).then(function(response){

            return response.json();

        }).then(function(responseData){

            _('success_message').innerHTML = responseData.success;

            table.update();

        });
    }
}


Above delete_data() function has send ajax request to action.php file for delete data operation. Below you can find the PHP script for delete data from Mysql table.

action.php

if($_POST['action'] == 'delete')
	{
		$query = "
		DELETE FROM customer_table 
		WHERE customer_id = '".$_POST["id"]."'
		";

		if($connect->query($query))
		{
			$output['success'] = '<div class="alert alert-success">Data Deleted</div>';

			echo json_encode($output);
		}
	}


So here our Vanilla DataTables CRUD Application is ready and under this Application we can load data in Vanilla DataTables, Insert or Add data with Bootstrap Modal, Update or Edit data with Bootstrap modal and lastly we can also perform delete data operation also. So here we have make Single Page Vanilla JavaScript CRUD Application with Fetch API and PHP script.

If you need complete source in single, so you can get by click on below button, once you have click on this button, then one dialog box will appear and it will ask you email address, so enter your valid email address, and once you have enter email address, then it will send source code file at your email address within 5 minutes. If you have not receive email in your inbox, please kindly check your SPAM folder also. Because our most of email goes in SPAM folder.







Sunday, 8 August 2021

Server Side Processing Vanilla JavaScript DataTables in PHP


If you are looking for Non jQuery version of DataTables which has been use pure vanilla JavaScript then you have come on the right place because in this tutorial we will show you how to use pure vanilla JavaScript DataTables with server side processing in PHP with dynamic Mysql table data. Currently most of the developer has use pure vanilla javascript in their web development. So if you have load data in jQuery DataTable but still you want to use jQuery DataTable then you have to include jQuery in your web application. But you want to perform all operation which you have perform in jQuery DataTable then here we have use Vanilla JavaScript DataTable in which you can perform all operation like searching, pagination, sorting etc under this Vanilla JavaScript DataTable without jQuery dependencies.

In this tutorial, we will use JSTable Javascript plugin which is lightweight and dependency free javascript and by using this plugin you can make your HTML table more interactive. This JSTable JavaScript library is very similar to jQuery DataTabes library but this JSTable library is not use jQuery but it has been used vanilla javascript.

This JSTable is a pure vanilla JavaScript based datatable component and it has features like we can load dynamic tabular data, we can filter or search data, we can sort data, it has automatically make pagination link and many more. By using JSTable library, we can perform server-side processing of data, which is inspired by jQuery datatables.

Under this tutorial, we will show you how to use this JSTable JavaScript DataTable in our web application and then after we will show you how can we perform server-side processing of data with PHP & Mysql under this JSTable JavaScript DataTable. Below you can find the complete source code of Vanilla DataTable Server-side Processing of Data in PHP.

Server Side Processing Vanilla JavaScript DataTable in PHP






Source Code


index.php



<?php

include('function.php');

?>

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="library/jstable.css" />

        <script src="library/jstable.min.js" type="text/javascript"></script>

        <title>Vanill JavaScript DataTables - Server-side Processing</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-success"><b>Vanill JavaScript DataTables - Server-side Processing in PHP</b></h1>

            <div class="card">
                <div class="card-header">Vanilla JavaScript DataTables</div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="customer_table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php echo fetch_top_five_data($connect); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

<script>

new JSTable('#customer_table', {
    serverSide:true,
    deferLoading : <?php echo count_all_data($connect); ?>,
    ajax : 'fetch.php'
});

</script>





function.php



<?php

//function.php

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5
	";

	$result = $connect->query($query);

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
		</tr>
		';
	}

	return $output;
}

function count_all_data($connect)
{
	$query = "SELECT * FROM customer_table";

	$statement = $connect->prepare($query);

	$statement->execute();

	return $statement->rowCount();
}

?>


fetch.php



<?php

//fetch.php

include('function.php');

/*This $_GET variable received in Ajax Request Url*/

//"start"			-	the data offset
$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);
$start = $startGET ? intval($startGET) : 0;

//"length"			-	the length of the returning data
$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);
$length = $lengthGET ? intval($lengthGET) : 10;

//"searchQuery"		- 	the search text
$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);
$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

//"sortColumn"  	-	the index of the to sorted column
$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

//"sortDirection"	-	the sorting direction (asc or desc)
$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
';

if($sortColumnIndex != '')
{
	$query .= 'ORDER BY ' . $column[$sortColumnIndex].' '.$sortDirection . ' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

$statement = $connect->prepare($query);

$statement->execute();

$number_filter_row = $statement->rowCount();

$result = $connect->query($query . $query1);

$data = array();

foreach($result as $row)
{
	$sub_array = array();

	$sub_array[] = $row['customer_first_name'];

	$sub_array[] = $row['customer_last_name'];

	$sub_array[] = $row['customer_email'];

	$sub_array[] = $row['customer_gender'];

	$data[] = $sub_array;
}

$output = array(
	'recordsTotal'			=>	count_all_data($connect),
	'recordsFiltered'		=>	$number_filter_row,
	'data'					=>	$data
);

echo json_encode($output);

?>