Showing posts with label data. Show all posts
Showing posts with label data. Show all posts

Friday, 1 September 2023

Efficient Node.js CRUD App with MySQL: Enhanced by Bootstrap Offcanvas for a Seamless User Experience

Efficient Node.js CRUD App with MySQL: Enhanced by Bootstrap Offcanvas for a Seamless User Experience


In today's fast-paced world of web development, creating applications that can seamlessly manage data is a must. That's where CRUD (Create, Read, Update, Delete) applications come into play, enabling users to interact with data stored in databases efficiently. In this article, we'll guide you through building an efficient Node.js CRUD application, supercharged by MySQL as the database, and enhanced with Bootstrap Offcanvas for an exceptional user experience.

Getting Started with Node.js and MySQL


Before diving into the Offcanvas enhancements, let's set the foundation by creating a basic Node.js CRUD application with MySQL. We'll go step by step:

Step 1: Setting Up Your Development Environment


Make sure you have Node.js and MySQL installed on your system. If not, you can download and install them from their respective websites.

Step 2: Project Initialization


Create a new directory for your project and navigate to it in your terminal. Run the following command to initialize a Node.js project:


npm init -y

Step 3: Installing Dependencies


Install the necessary dependencies: express, mysql2, and body-parser using the following command:


npm install express mysql2 body-parser


Step 4: Creating the Server


Now, create a server.js file and set up your Express server. Import the required modules and configure your server:


const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const app = express();

app.use(bodyParser.urlencoded({ extended : true }));

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	}
	console.log('Connected to MySQL database');
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});


Step 5: Setting Up CRUD Routes


Implement your CRUD operations by defining routes for creating, reading, updating, and deleting data in your MySQL database. Here's a simplified example for the "read" operation:

Index Route

When someone navigates to the root URL of our server, we serve an HTML file named form.html. We're essentially setting up the initial interface for users to interact with.


app.get('/', (request, response) => {
	response.sendFile(__dirname + '/form.html');
});


Select or Fetch Data


This route will handle requests for fetching data from our MySQL database.


app.get('/fetchData', (request, response) => {
	const { draw, start, length, order, columns, search } = request.query;

	const column_index = order && order[0] && order[0].column;

	const column_sort_order = order === undefined ? 'desc' : request.query.order[0]['dir'];

	const column_name = column_index ? columns[column_index] : 'id';

	const search_value = search.value;

	const search_query = search_value ? ` WHERE name LIKE '%${search_value}%' OR email LIKE '%${search_value}%'` : '';

	const query1 = `SELECT id, name, email FROM user ${search_query} ORDER BY ${column_name} ${column_sort_order} LIMIT ${start}, ${length}`;

	const query2 = `SELECT COUNT(*) AS Total FROM user`;

	const query3 = `SELECT COUNT(*) AS Total FROM user ${search_query}`;

	connection.query(query1, (dataError, dataResult) => {

		connection.query(query2, (totalDataError, totalDataResult) => {

			connection.query(query3, (totalFilterDataError, totalFilterDataResult) => {

				response.json({
					draw : request.query.draw,
					recordsTotal : totalDataResult[0]['Total'],
					recordsFiltered : totalFilterDataResult[0]['Total'],
					data : dataResult
				});

			})

		})

	})
});


Insert Update Delete Data


This route will handle requests for Insert Update Delete data from our MySQL database.


app.post('/submitData', (request, response) => {
	const id = request.body.id;
	const name = request.body.name;
	const email = request.body.email;
	const action = request.body.action;
	let query;
	let data;
	let message;
	if(action === 'Insert'){
		query = `INSERT INTO user (name, email) VALUES (?, ?)`;
		data = [name, email];
		message = 'Data has been inserted';
	}

	if(action === 'Edit'){
		query = `UPDATE user SET name = ?, email = ? WHERE id = ?`;
		data = [name, email, id];
		message = 'Data has been updated';
	}

	if(action === 'Delete'){
		query = `DELETE FROM user WHERE id = ?`;
		data = [id];
		message = 'Data has been deleted';
	}

	connection.query(query, data, (error, result) => {
		response.json({'message' : message});
	});
});


Fetch Single Data


This route will be used for fetch single data from MySQL Database.


app.get('/fetchData/:id', (request, response) => {
	const query = `SELECT * FROM user WHERE id = ?`;

	connection.query(query, [request.params.id], (error, result) => {
		response.json(result[0]);
	});
});





Enhancing User Experience with Bootstrap Offcanvas


Now that we have our Node.js CRUD application up and running, it's time to enhance the user experience with Bootstrap Offcanvas. The Offcanvas component provides a sleek and non-intrusive way to interact with data.

Step 1: Adding Bootstrap to Your Project


Include Bootstrap CSS and JavaScript files in your HTML. You can either download them and host them locally or use a Content Delivery Network (CDN). Here's an example of using CDN links:


<!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 href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <title>Node.js CRUD with MySQL & Bootstrap Offcanvas</title>
    </head>
    <body>

        <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    </body>
</html>


Step 2: Creating an Offcanvas


Now, let's implement an Offcanvas for editing user data. Add a button to trigger the Offcanvas:


<button type="button" class="btn btn-primary btn-sm float-end" onclick="addData()">Add</button>


Create the Offcanvas element with a form for editing user data:


<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvas_component">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title" id="offcanvasLabel">Add Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">

            </div>
        </div>


Step 3: Implementing the Edit Form


Inside the Offcanvas body, add a form for adding or editing user data. So for this, we have make form field by using javascript function which we can you for both Insert or updata of data also.


function makeForm(id = '', name = '', email = '', action = 'Insert')
    {
        const output = `
        <div class="mb-3">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" class="form-control" value="${name}" />
        </div>
        <div class="mb-3">
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" class="form-control" value="${email}" />
        </div>
        <input type="hidden" name="action" id="action" value="${action}" />
        <input type="hidden" name="id" id="id" value="${id}" />
        <input type="submit" class="btn btn-primary" onclick="submitForm();" value="${action}" />
        `;
        return output;
    }


Step 4: JavaScript for Offcanvas Interaction


Finally, use JavaScript to handle the Offcanvas interactions. Add an event listener to open the Offcanvas when the "Edit User" button is clicked:


let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    let offcanvasLabel = document.querySelector('#offcanvasLabel');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);


You can further enhance this by pre-populating the form with user data for editing and implementing the update functionality.

Complete Source Code


server.js

const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const app = express();

app.use(bodyParser.urlencoded({ extended : true }));

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	}
	console.log('Connected to MySQL database');
});

app.get('/', (request, response) => {
	response.sendFile(__dirname + '/form.html');
});

app.get('/fetchData', (request, response) => {
	const { draw, start, length, order, columns, search } = request.query;

	const column_index = order && order[0] && order[0].column;

	const column_sort_order = order === undefined ? 'desc' : request.query.order[0]['dir'];

	const column_name = column_index ? columns[column_index] : 'id';

	const search_value = search.value;

	const search_query = search_value ? ` WHERE name LIKE '%${search_value}%' OR email LIKE '%${search_value}%'` : '';

	const query1 = `SELECT id, name, email FROM user ${search_query} ORDER BY ${column_name} ${column_sort_order} LIMIT ${start}, ${length}`;

	const query2 = `SELECT COUNT(*) AS Total FROM user`;

	const query3 = `SELECT COUNT(*) AS Total FROM user ${search_query}`;

	connection.query(query1, (dataError, dataResult) => {

		connection.query(query2, (totalDataError, totalDataResult) => {

			connection.query(query3, (totalFilterDataError, totalFilterDataResult) => {

				response.json({
					draw : request.query.draw,
					recordsTotal : totalDataResult[0]['Total'],
					recordsFiltered : totalFilterDataResult[0]['Total'],
					data : dataResult
				});

			})

		})

	})
});

app.post('/submitData', (request, response) => {
	const id = request.body.id;
	const name = request.body.name;
	const email = request.body.email;
	const action = request.body.action;
	let query;
	let data;
	let message;
	if(action === 'Insert'){
		query = `INSERT INTO user (name, email) VALUES (?, ?)`;
		data = [name, email];
		message = 'Data has been inserted';
	}

	if(action === 'Edit'){
		query = `UPDATE user SET name = ?, email = ? WHERE id = ?`;
		data = [name, email, id];
		message = 'Data has been updated';
	}

	if(action === 'Delete'){
		query = `DELETE FROM user WHERE id = ?`;
		data = [id];
		message = 'Data has been deleted';
	}

	connection.query(query, data, (error, result) => {
		response.json({'message' : message});
	});
});

app.get('/fetchData/:id', (request, response) => {
	const query = `SELECT * FROM user WHERE id = ?`;

	connection.query(query, [request.params.id], (error, result) => {
		response.json(result[0]);
	});
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});




form.html

<!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 href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <title>Node.js CRUD with MySQL & Bootstrap Offcanvas</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-danger text-center mt-3"><b>Node.js CRUD with MySQL & Bootstrap Offcanvas - Delete Data</b></h1>
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-11"><b>Node.js CRUD with MySQL & Bootstrap Offcanvas</b></div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-primary btn-sm float-end" onclick="addData()">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvas_component">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title" id="offcanvasLabel">Add Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">

            </div>
        </div>

        <!-- Optional JavaScript; choose one of the two! -->

        <!-- Option 1: Bootstrap Bundle with Popper -->
        


        <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    </body>
</html>

<script>

$(document).ready(function(){

    $('#sample_data').DataTable({
        ajax : '/fetchData',
        processing : true,
        serverSide : true,
        serverMethod : 'GET',
        order : [],
        columns : [
            { data : 'name' },
            { data : 'email' },
            {
                data : null,
                render : function (data, type, row){
                    return `<button class="btn btn-warning btn-sm" onclick="fetchData(${data.id})">Edit</button>&nbsp;<button class="btn btn-danger btn-sm" onclick="deleteData(${data.id})">Delete</button>`;
                }
            }
        ]
    });

});

    let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    let offcanvasLabel = document.querySelector('#offcanvasLabel');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);

    function addData()
    {
        offcanvas_body.innerHTML = makeForm();
        offcanvas.show();
    }

    function makeForm(id = '', name = '', email = '', action = 'Insert')
    {
        const output = `
        <div class="mb-3">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" class="form-control" value="${name}" />
        </div>
        <div class="mb-3">
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" class="form-control" value="${email}" />
        </div>
        <input type="hidden" name="action" id="action" value="${action}" />
        <input type="hidden" name="id" id="id" value="${id}" />
        <input type="submit" class="btn btn-primary" onclick="submitForm();" value="${action}" />
        `;
        return output;
    }

    function submitForm()
    {
        const id = document.querySelector('#id').value;
        const name = document.querySelector('#name').value;
        const email = document.querySelector('#email').value;
        const action = document.querySelector('#action').value;

        $.ajax({
            url : '/submitData',
            method : 'POST',
            data : {id : id, name : name, email : email, action : action},
            dataType : 'JSON',
            success : function(data){
                $('#sample_data').DataTable().ajax.reload();
                offcanvas.hide();
                alert(data.message);
            }
        });
    }

    function fetchData(id)
    {
        $.ajax({
            url : '/fetchData/'+id,
            dataType : 'JSON',
            success : function(data){
                offcanvas_body.innerHTML = makeForm(data.id, data.name, data.email, 'Edit');
                offcanvasLabel.innerHTML = 'Edit Data';
                offcanvas.show();
            }
        });
    }

    function deleteData(id){
        let output = `
        <div class="text-center">
            <h3 class="text-danger mb-4">Are you sure you want to remove this data?</h3>
            <input type="hidden" id="id" value="${id}" />
            <input type="hidden" id="action" value="Delete" />
            <input type="hidden" id="name" value="" />
            <input type="hidden" id="email" value="" />
            <button type="button" class="btn btn-info" onclick="submitForm()">OK</button>
            <button type="button" class="btn btn-default" data-bs-dismiss="offcanvas">Cancel</button>
        </div>
        `;

        offcanvas_body.innerHTML = output;
        offcanvasLabel.innerHTML = 'Delete Data Confirmation';
        offcanvas.show();
    }

</script>


Run Node Application


For run Node.js Application, we have goes to terminal and goes into our working directory and run following command.


node server.js


This command will start our Node server and for check output in browser, we have to open this url in the browser window.


http://localhost:3000/


Conclusion


In this article, we've walked through the process of building an efficient Node.js CRUD application with MySQL. We've also explored how to enhance the user experience by integrating Bootstrap Offcanvas for a seamless and visually appealing interface. By combining the power of Node.js, MySQL, and Bootstrap Offcanvas, you can create dynamic and user-friendly applications that excel in data management.

Now, it's your turn to explore and expand upon these concepts to build feature-rich CRUD applications tailored to your specific requirements. Happy coding!

Saturday, 16 July 2022

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5


In this tutorial, we are going to show you how to make CRUD Application Laravel 9 framework. We will explained you step by step, how can we perform CRUD Operation in Laravel 9 Framework. So if you beginner in Laravel framework then this tutorial will help you to build CRUD Application in Laravel 9 framework, and you will be able to create Laravel 9 CRUN Application. Here under this tutorial, we will use basic example to show you CRUD Operation in Laravel 9.

Recently Laravel has release Laravel 9 framework and in Laravel 9 framework there is several new features and LTS Support. Laravel 9 also introduced an Anonymous Sub Migration also and it also resolved migration class name Collison. One more things Laravel 9 framework has been use PHP 8 version and it has been support PHP string function, which are very useful for string operations. There are many new query builder function has been introduced under Laravel 9 framework which will more convenient when you have work with database operation. So you are learn Laravel framework first time then this tutorial will help you to create CRUD (Create, Read, Update and Delete) Operation in Laravel 9 framework.

In this tutorial, we will create Student CRUD Application in Laravel 9 framework. Under this CRUD Application we will make Application, in which we can Add new Student Data, with student image upload, edit or change existing student data, with form data validation, show single student data on the web page, delete or remove student data from data and fetch all student data from MySQL database and display on the web page in HTML table format with dynamic pagination link. We will also create table in MySQL database from this Laravel 9 application using Laravel 9 Migration, and after this, we will create Controller, Models and views file for student crud application. Under this Laravel 9 crud application we will use Bootstrap 5 library for design web page. You have to following below steps to create CRUD Application in Laravel 9 framework.


Step 1 - Download & Install 9


In the First Steps of Laravel 9 CRUD Application, we have to download and install fresh Laravel 9 Application in our computer. So for this, you have to goes to command prompt and then after goes into directory where you have run PHP 8 script and then after you have to run following command.


composer create-project --prefer-dist laravel/laravel laravel_9_crud


Once we have run this command then it will create laravel_9_crud directory and under this directory it will download and install Laravel 9 Application.

Step 2 - Make Database Connection


After install Laravel 9 application, first we need to create database connection with MySQL database. So for this we have to open .env file and under this file, we need to add MySQL database configuration like MySQL database name, MySQL database user namd and password details. Once we have define this details, then it will make MySQL database connection in Laravel 9 framework. Below you can find MySQL database configuration details.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 - Create MySQL Table using Laravel 9 Migration


Under this step, we have to crate students table under MySQL database from this Laravel 9 Application using Migrations. So first we have to create migration file under Laravel 9 application, so we have to run following command in command prompt.


php artisan make:migration create_students_table --create=students


After run above command then you will find one new file under database/migrations directory. So for we have to open that file and under that file, we have to define following code under that migrations file for create students table in MySQL database.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('student_name');
            $table->string('student_email');
            $table->enum('student_gender', ['Male', 'Female']);
            $table->string('student_image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};



After above code in migration file, now for create table in MySQL database from this Laravel 9 application, so for this, we have to run following command in command prompt and it will migrate MySQL table defination to MySQL database and create students table in MySQL database from this Laravel 9 Application.


php artisan migrate





Step 4 - Create CRUD Model and Controller


Under this step, we have to create Controller and Models file for CRUD Operation. So for this, we have goes to command prompt and run following command, which will create new CRUD StudentController and Student Model class file under Laravel 9 framework.


php artisan make:controller StudentController --resource --model=Student


So after run above command it will create Student.php model class file under app/Models directory and we have to open that file and put following code under that file.

app/Models/Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    protected $fillable = ['student_name', 'student_email', 'student_gender', 'student_image'];
}



And after run above command it will also create CRUD Controller with name StudentController.php file under app/Http/Controllers directory.

So this StudentController.php file has been created with seven method by default which you can seen below.

  1. index() - This is root method of this Controller class.
  2. create() - This is method has been used for load Add student form in the browser.
  3. store() - This method has been used for handle Add student data request.
  4. show() - This method has been used for display single student data on the web page.
  5. edit() - This method has been used for load edit student form in the browser.
  6. update() - This method has been receive student update form data request.
  7. destroy() - This method has been used for delete student data from database.

For create CRUD Application, you have to put folliowing code under StudentController.php file.

app/Http/Controllers/StudentController.php app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Student::latest()->paginate(5);

        return view('index', compact('data'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'student_name'          =>  'required',
            'student_email'         =>  'required|email|unique:students',
            'student_image'         =>  'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $file_name = time() . '.' . request()->student_image->getClientOriginalExtension();

        request()->student_image->move(public_path('images'), $file_name);

        $student = new Student;

        $student->student_name = $request->student_name;
        $student->student_email = $request->student_email;
        $student->student_gender = $request->student_gender;
        $student->student_image = $file_name;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        return view('show', compact('student'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit(Student $student)
    {
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Student $student)
    {
        $request->validate([
            'student_name'      =>  'required',
            'student_email'     =>  'required|email',
            'student_image'     =>  'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $student_image = $request->hidden_student_image;

        if($request->student_image != '')
        {
            $student_image = time() . '.' . request()->student_image->getClientOriginalExtension();

            request()->student_image->move(public_path('images'), $student_image);
        }

        $student = Student::find($request->hidden_id);

        $student->student_name = $request->student_name;

        $student->student_email = $request->student_email;

        $student->student_gender = $request->student_gender;

        $student->student_image = $student_image;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Data has been updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy(Student $student)
    {
        $student->delete();

        return redirect()->route('students.index')->with('success', 'Student Data deleted successfully');
    }
}



Step 5 - Add Service Provider for Bootstrap Pagination


In Laravel 9 framework produce default style pagination link which will not properly display if you have Bootstrap library. So for this, we have to open app/Providers/AppServiceProvider.php and under this file, we have to add Paginator::useBootstrap() code under boot() method for support the bootstrap pagination.

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}



So after adding this code, you Laravel 9 application will display proper pagination link on the web page.

Step 6 - Create Views Blades File


Under this steps, we have to create blades files for display HTML output in the browser. In the Laravel 9 framework, blades files has been stored under resources/views directory. Under this Laravel 9 CRUD Application, we have to create following views blades files.

  1. master.blade.php - This is master template file.
  2. index.blade.php - This file we will used for display MySQL table data on the web page in HTML table format with pagination link.
  3. create.blade.php - This file has been used for load Create Student form on the web page.
  4. show.blade.php - This file has been used for display single student data on the web page.
  5. edit.blade.php - This file has been used for load student edit form in the browser.

Below you can find source code of all blade file.

resources/views/master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 CRUD Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        
        <h1 class="text-primary mt-3 mb-4 text-center"><b>Laravel 9 Crud Application</b></h1>
        
        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/index.blade.php

@extends('master')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-success">
	{{ $message }}
</div>

@endif

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Data</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.create') }}" class="btn btn-success btn-sm float-end">Add</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<table class="table table-bordered">
			<tr>
				<th>Image</th>
				<th>Name</th>
				<th>Email</th>
				<th>Gender</th>
				<th>Action</th>
			</tr>
			@if(count($data) > 0)

				@foreach($data as $row)

					<tr>
						<td><img src="{{ asset('images/' . $row->student_image) }}" width="75" /></td>
						<td>{{ $row->student_name }}</td>
						<td>{{ $row->student_email }}</td>
						<td>{{ $row->student_gender }}</td>
						<td>
							<form method="post" action="{{ route('students.destroy', $row->id) }}">
								@csrf
								@method('DELETE')
								<a href="{{ route('students.show', $row->id) }}" class="btn btn-primary btn-sm">View</a>
								<a href="{{ route('students.edit', $row->id) }}" class="btn btn-warning btn-sm">Edit</a>
								<input type="submit" class="btn btn-danger btn-sm" value="Delete" />
							</form>
							
						</td>
					</tr>

				@endforeach

			@else
				<tr>
					<td colspan="5" class="text-center">No Data Found</td>
				</tr>
			@endif
		</table>
		{!! $data->links() !!}
	</div>
</div>

@endsection


resources/views/create.blade.php

@extends('master')

@section('content')

@if($errors->any())

<div class="alert alert-danger">
	<ul>
	@foreach($errors->all() as $error)

		<li>{{ $error }}</li>

	@endforeach
	</ul>
</div>

@endif

<div class="card">
	<div class="card-header">Add Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.store') }}" enctype="multipart/form-data">
			@csrf
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
				</div>
			</div>
			<div class="text-center">
				<input type="submit" class="btn btn-primary" value="Add" />
			</div>	
		</form>
	</div>
</div>

@endsection('content')


resources/views/show.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Details</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.index') }}" class="btn btn-primary btn-sm float-end">View All</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Name</b></label>
			<div class="col-sm-10">
				{{ $student->student_name }}
			</div>
		</div>
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Email</b></label>
			<div class="col-sm-10">
				{{ $student->student_email }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Gender</b></label>
			<div class="col-sm-10">
				{{ $student->student_gender }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Image</b></label>
			<div class="col-sm-10">
				<img src="{{ asset('images/' .  $student->student_image) }}" width="200" class="img-thumbnail" />
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/edit.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">Edit Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.update', $student->id) }}" enctype="multipart/form-data">
			@csrf
			@method('PUT')
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" value="{{ $student->student_name }}" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" value="{{ $student->student_email }}" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
					<br />
					<img src="{{ asset('images/' . $student->student_image) }}" width="100" class="img-thumbnail" />
					<input type="hidden" name="hidden_student_image" value="{{ $student->student_image }}" />
				</div>
			</div>
			<div class="text-center">
				<input type="hidden" name="hidden_id" value="{{ $student->id }}" />
				<input type="submit" class="btn btn-primary" value="Edit" />
			</div>	
		</form>
	</div>
</div>
<script>
document.getElementsByName('student_gender')[0].value = "{{ $student->student_gender }}";
</script>

@endsection('content')


Step 7 - Set Resource Route


Under this step, we have to add resource route for student crud application. So for set route, we have to open routes/web.php file and under this file, we have to define resource route for Laravel 9 CRUD Application.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


Route::resource('students', StudentController::class);


After adding above code, then it will set route for all method of StudentController.php file.

Step 8 - Run Laravel 9 CRUD Application


When we have follow all above steps, that means our Laravel 9 CRUD Application is ready for check output in the browser. So for check output in the browser, first we need to start Laravel 9 Application server, so for this, we have go to command prompt and run following command.


php artisan serve


So this command will start Laravel server and provide us base url of our Laravel 9 CRUD Application. So we have goes to browser, and type give below URL and view output of Laravel 9 CRUD Application.


http://127.0.0.1:8000/students


So this is complete step by step tutorial on Laravel 9 CRUD Application, so you have follow all above steps then you can able to learn How to perform Insert, Update, Delete and Read MySQL Data Operation in Laravel 9 framework and build CRUD Application Laravel 9 framework with MySQL database and Bootstrap 5 Library.

Laravel 9 CRUD Application Video Tutorial


1 - Load MySQL Data in HTML Table with Pagination Links



2 - Insert or Add Data into MySQL Table



3 - Retrieve MySQL Data & Display on Web page



4 - Update or Edit MySQL Data



5 - Delete or Remove Data From MySQL



Thursday, 7 July 2022

Export MySQL Data to CSV File using Node.js Express


This tutorial on Export Data to CSV file using Node js Express Application and in this tutorial, you will learn how to export data in CSV file from MySQL Database table in Node.js Application.

In our Node Web Application, sometimes we have to export data from MySQL database. So at that time CSV file format is the best option for exporting data from MySQL Database, so for this here in our Node.js Express Application, we will export MySQL data to CSV file using Node.js Application.

So if you have follow this tutorial, then this tutorial will helps you in easy way to exporting mysql database table data in CSV file using Node JS Express framework.

In this Node.js tutorial on export data to CSV file, we will use body-parser and json2csv node module under this node application, and by using this both module we will first export data to CSV file.

  • Fetch data from MySQL and display on Web page in HTML table format using Node.js & MySQL
  • Fetch Data from MySQL table and convert into JSON format
  • Convert JSON data to CSV format using json2csv node module
  • Export MySQL data to CSV file and download CSV file using Node.js

Export MySQL Data to CSV File using Node.js Express

For Export MySQL data to CSV file in Node.js, so you have follow below steps.

  1. MySQL Table Structure
  2. Download and Install Node.js Express framework
  3. Create MySQL Database Connection
  4. Install body-parser & json2csv Module
  5. Create Routes
  6. Create Views File
  7. Check Output in the browser




Step 1 - MySQL Table Structure


For start this tutorial, first we have to create table in MySQL table for export data to CSV file format in Node.js, so for create table in MySQL database, we have to run following script in your phpmyadmin area and it will create sample_data table with pre inserting of sample data and we will export that data to CSV file using Node js.


--
-- Database: `testing`
--

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

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

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `age` varchar(30) NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sample_data`
--

INSERT INTO `sample_data` (`id`, `first_name`, `last_name`, `age`, `gender`) VALUES
(1, 'John', 'Smith', '26', 'Male'),
(2, 'Donna', 'Hubber', '24', 'Female'),
(3, 'Peter', 'Parker', '28', 'Male'),
(4, 'Tom ', 'Muddy', '28', 'Male'),
(5, 'Desmond', 'Taylor', '36', 'Male'),
(6, 'Willie', 'Hudson', '24', 'Male'),
(7, 'Harold', 'Avila', '29', 'Male'),
(8, 'Kathryn', 'Moon', '22', 'Female'),
(9, 'Maria', 'Brewer', '26', 'Female'),
(10, 'Carma', 'Holland', '25', 'Female'),
(11, 'Patrick', 'Michel', '32', 'Male');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;





Step 2 - Download and Install Node.js Express framework


In this Node.js tutorial, we have use Express.js Framework, So first we need to download and install Node.js Express framework. So for this, first we have to go into directory in which we have run our node code and under that directory, we have to create csv_export directory and then after we have goes into that directory, so for this, we have to run following command.


mkdir csv_export
cd csv_export


Once we have goes into csv_export directory, now first we wan to download and install node express genderator, so for this, in the command prompt we have to run following command, which will download and install node.js express generator.


npm install -g express-generator


Next we want to download and install node.js express framework, so for this in the command prompt we have to run following command which will download and install node.js express framework under autocomplete directory.


npx express --view=ejs


In this downloaded Node.js Express framework, we have use ejs template engine for display HTML output in the browser and once we have run this command then it will display following node.js express directory structure which you can seen below.


create : public\
   create : public\javascripts\
   create : public\images\
   create : public\stylesheets\
   create : public\stylesheets\style.css
   create : routes\
   create : routes\index.js
   create : routes\users.js
   create : views\
   create : views\error.ejs
   create : views\index.ejs
   create : app.js
   create : package.json
   create : bin\
   create : bin\www

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=crud:* & npm start


And lastly under node.js express download and install process we have to run following command for install required node.js default module for express framework.


npm install


After run above command, so here our Node.js Express download and install process is completed.

Step 3 - Create MySQL Database Connection


After download and install Node.js Express framework, now we want to connect this applicatioin with MySQL Database, so for make MySQL database connection, first we have to download node mysql module. So for this, we have to run following command in command prompt.


npm install mysql


Once Node Mysql module has been install in our node express application, next we need to create one database.js file for create mysql database connection, and under this file, we have to define MySQL database configuration for connection node express application with MySQL database.

database.js

const mysql = require('mysql');

var connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

connection.connect(function(error){
	if(error)
	{
		throw error;
	}
	else
	{
		console.log('MySQL Database is connected Successfully');
	}
});

module.exports = connection;


Step 4 - Install body-parser & json2csv Module


In this Node tutorial for Export data to CSV, here we need to download some extra node module like body-parser and json2csv module. So for download this module, we have goes to command prompt and run following command.


npm install body-parser json2csv --save


In this above command json2csv module has been used for convert a JSON data to CSV data and convert CSV data to JSON format.

And body-parser module is a npm library which has been process data and send that data to HTTP request body.

So by isntalling this both module under this Node Express framework, we can able to export MySQL database to CSV file format.

Step 5 - Create Routes


In the Node Express framework, routes file has been used for handle HTTP request. Here when we have download express framework, then you will get index.js default files under routes directory.

Here we have to open routes/index.js file and under this file, we have to include database connection file and json2csv node module also.

After this, in the main route which has been load views/index.ejs file for display output in the browser. So when file has been load then it will fetch data from MySQL table and display data on the web page in HTML table format.

And for handle request for export data to csv file, we have to create another route and under that route first it will fetch data from mysql table, and convert that data into JSON format and lasly by using json2csv module it will convert json data to csv format and downlaod csv file in local computer.

routes/index.js

var express = require('express');
var router = express.Router();

var database = require('../database');

var data_exporter = require('json2csv').Parser;

/* GET home page. */
router.get('/', function(req, res, next) {

    database.query('SELECT * FROM sample_data', function(error, data){

        res.render('index', { title: 'Express', sample_data:data });

    });
    
});

router.get('/export', function(request, response, next){

    database.query('SELECT * FROM sample_data', function(error, data){

        var mysql_data = JSON.parse(JSON.stringify(data));

        //convert JSON to CSV Data

        var file_header = ['First Name', 'Last Name', 'Age', 'Gender'];

        var json_data = new data_exporter({file_header});

        var csv_data = json_data.parse(mysql_data);

        response.setHeader("Content-Type", "text/csv");

        response.setHeader("Content-Disposition", "attachment; filename=sample_data.csv");

        response.status(200).end(csv_data);

    });

});

module.exports = router;


Step 6 - Create Views File


In the Node.js Express framework, views directory file has been used for display html output in the browser. In this tutorial, we have use EJS template engine for display HTML output in the browser. Here we will use views/index.ejs default file, and under this file, first we will display mysql data in html table format and then after, we have to create on link for export data to csv file which will send http get request to routes for export data to csv file in Node.js Express application.

views/index.ejs

<!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">

        <title>How to Export MySQL Data to CSV in Node.js</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center text-primary mt-3 mb-3">How to Export MySQL Data to CSV in Node.js</h1>

            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">Sample Data</div>
                        <div class="col-md-2">
                            <a href="/export" class="btn btn-success btn-sm float-end">Export to CSV</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                        
                    <table class="table table-bordered">
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Age</th>
                            <th>Gender</th>
                        </tr>
                        <% sample_data.forEach(function(data){ %>
                        <tr>
                            <td><%= data.first_name %></td>
                            <td><%= data.last_name %></td>
                            <td><%= data.age %></td>
                            <td><%= data.gender %></td>
                        </tr>
                        <% }); %>
                    </table>

                </div>
            </div>
        </div>
  </body>
</html>


Step 7 - Check Output in the browser


Once we have follow all above step, so we are able to check output in the browser. So for check output in the browser, first we have goes to command prompt and run following command.


npm start


This command will start Node.js server and then after we can goes to browser and following URL.


http://localhost:3000/


So once we have hit above url then it will display MySQL table data on web page in HTML table format and above this data, we can see on export button. So when we have click on export button then it will export mysql data into CSV file format using Node js express application.





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.