Vanilla DataTables CRUD using PHP and MySQL Database Tutorial
Introduction
In this tutorial, you will learn to Create CRUD Functionalities using the Vanilla DataTables, PHP, and MySQL Database. This tutorial aims to provide a reference or a guide to beginners or new programmers to enhance their PHP and JS programming capabilities. Here, snippets and sample source code are provided and the source code file is free to download.
What is Vanilla DataTables?
The Vanilla DataTables is a lightweight, extendable, dependency-free javascript HTML table plugin. It is like a VanillaJS version of the jQuery DataTables Plugin which has a lot of options, methods, and events for managing or manipulating the HTML table on the client side. This plugin contains multiple functionalities such as sorting, searchable, pagination, and more. To know more, visit https://github.com/Mobius1/Vanilla-DataTables.
How to CRUD Functionalities in Vanilla DataTables using PHP and MySQL Database?
There are a lot of ways to create CRUD (Create, Read, Update, and Delete) functionalities for Vanilla DataTables Data using PHP and MySQL Database. Here, I will show you how it is being done effectively by using the following technologies.
- HTML
- Plain JavaScript
- Vanilla DataTables Plugin
- PHP
- MySQL Database
- Bootstrap Framework
Getting started
First, download XAMPP or any equivalent software to run PHP Script and MySQL Database on your local machine. For those who are using XAMPP, open the XAMPP's Control Panel and start Apache and MySQL.
Download Vanilla DataTables
Next, download the Vanilla DataTables plugin at https://github.com/Mobius1/Vanilla-DataTables or you can also use the provided CDNs of the plugin library.
Creating the Database
Next, create the sample database that we need for this tutorial. Create a new database named dummy_db. Then use the following MySQL Schema to create the sample table.
Let's do the Coding Part
Database Connection
The below snippets is a PHP Script that handles the database connection between the web application and the MySQL Database.
db-connect.php
- <?php
- $host = "localhost";
- $username = "root";
- $pw = "";
- $db_name = "dummy_db";
- $conn = new mysqli($host, $username, $pw, $db_name);
- if(!$conn){
- }
- ?>
Creating the Backend/API
The following snippet is a PHP Script that contains the CRUD functionalities on the backend. The script handles all Insert, Update, Retrieve, and Delete Data on the Database.
api.php
- <?php
- require_once('db-connect.php');
- /**
- * Fetch All Members
- */
- function get_data(){
- global $conn;
- $sql = "SELECT * FROM `members` order by `id` asc";
- $qry = $conn->query($sql);
- $data = [];
- if($qry->num_rows > 0){
- while($row = $qry->fetch_assoc()){
- $data[] = [
- 'id' => $row['id'],
- 'name' => $row['name'],
- 'contact' => $row['contact'],
- 'address' => $row['address'],
- 'action' => $row['id']
- ];
- }
- }
- $conn->close();
- }
- /**
- * Insert/Update Member
- */
- function save_member(){
- global $conn;
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $id = $_POST['id'];
- $sql = "INSERT INTO `members` (`name`, `contact`, `address`)
- VALUES ('{$name}', '{$contact}', '{$address}')";
- }else{
- $sql = "UPDATE `members` set `name` = '{$name}', `contact` = '{$contact}', `address` = '{$address}' where `id` = '{$id}' ";
- }
- $save = $conn->query($sql);
- if($save){
- $resp['status'] ='success';
- }else{
- $resp['status'] ='failed';
- $resp['error'] =$conn->error;
- }
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = "Request must be using POST Method.";
- }
- $conn->close();
- }
- /**
- * Fetch Single Member Data
- */
- function get_single(){
- global $conn;
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $id = $_POST['id'];
- $sql = "SELECT * FROM `members` where id = '{$id}'";
- $get = $conn->query($sql);
- if($get->num_rows > 0){
- $resp['status'] = 'success';
- $resp['data'] = $get->fetch_assoc();
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = "Member ID does not exists.";
- }
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = "Request must be using POST Method.";
- }
- $conn->close();
- }
- /**
- * Delete Member Data
- */
- function delete_member(){
- global $conn;
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $id = $_POST['id'];
- $sql = "DELETE FROM `members` where id = '{$id}'";
- $delete = $conn->query($sql);
- if($delete){
- $resp['status'] = 'success';
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = $conn->error;
- }
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = "Request must be using POST Method.";
- }
- $conn->close();
- }
- $exec = $action();
- echo $exec;
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = 'Invalid Given Action';
- return $resp;
- }
- }else{
- $resp['status'] = 'failed';
- $resp['error'] = 'Action must not be empty';
- return $resp;
- }
Creating the JavaScript
The snippet below is a JavaScript file that contains all the functionalities of the web application on the client side. The script below is not dependent on any other JavaScript library or framework except for the Vanilla DataTables Plugin and Bootstrap v5 Modal.
app.js
- var formModal,
- vanillaDT,
- modal,
- memberForm;
- document.addEventListener('DOMContentLoaded', () => {
- /**
- * Initialize Vanilla JS DataTabale
- */
- var dt_option = {
- columns: [{
- select : 3 ,
- render: function(data){
- return data.replaceAll(/\n\r/gi,'<br>');
- }
- },{
- select : 4 ,
- render: function(data){
- return `<div class="text-center">
- <button class="btn btn-outline-primary btn-sm rounded-0" type="button" onclick="edit_member(${data})">
- <i class="fa-solid fa-edit"></i>
- </button>
- <button class="btn btn-outline-danger btn-sm rounded-0" type="button" onclick="delete_member(${data})">
- <i class="fa-solid fa-trash"></i>
- </button>
- <div class="text-center">
- `;
- }
- }],
- ajax:'api.php?action=get_data'
- }
- vanillaDT = new DataTable('#memberTable',dt_option)
- /**
- * Form Modal
- */
- modal = document.getElementById('memberFormModal')
- formModal = new bootstrap.Modal('#memberFormModal', {
- backdrop :'static'
- })
- memberForm = document.getElementById('member-form')
- document.getElementById('add_new').addEventListener('click', function(){
- modal.querySelector('.modal-title').innerText = `Add New Member`
- formModal.show()
- })
- modal.addEventListener('hide.bs.modal', function(){
- memberForm.reset()
- })
- /**
- * Form Submission
- */
- memberForm.addEventListener('submit', (e) => {
- e.preventDefault()
- var formData = new FormData(memberForm)
- modal.querySelectorAll('.btn, button').forEach( el => { el.setAttribute('disabled',true) } )
- fetch('api.php?action=save_member', {
- method: 'POST',
- body: formData
- }).then(resp=>{
- return resp.json();
- }).then(data => {
- if(!!data.status){
- if(data.status == 'success'){
- alert(`Member's Data has been saved successfully.`);
- vanillaDT.destroy()
- vanillaDT.init()
- }else if(!!data.error){
- alert("Saving Member's Data Failed due to some error.");
- console.log(data.error)
- }else{
- alert("Saving Member's Data Failed due to some error.");
- }
- }else{
- alert("Saving Member's Data Failed due to some error.");
- }
- modal.querySelectorAll('.btn, button').forEach( el => { el.removeAttribute('disabled') } )
- formModal.hide();
- }).catch((error) => {
- console.error(error)
- modal.querySelectorAll('.btn, button').forEach( el => { el.removeAttribute('disabled') } )
- });
- })
- } )
- /**
- * Edit Member Function
- * @param {*} $id
- */
- function edit_member($id=0){
- var formData = new FormData();
- formData.append('id', $id)
- fetch('api.php?action=get_single',{
- method:'POST',
- body:formData
- })
- .then(resp => {
- return resp.json();
- })
- .then(data => {
- if(!!data.status){
- if(data.status == 'success'){
- memberForm.querySelector('input[name="id"]').value = data.data.id
- memberForm.querySelector('input[name="name"]').value = data.data.name
- memberForm.querySelector('input[name="contact"]').value = data.data.contact
- memberForm.querySelector('textarea[name="address"]').value = data.data.address
- modal.querySelector('.modal-title').innerText = "Edit Member's Data";
- formModal.show()
- }else if(!!data.error){
- alert("Fetching Data Failed.")
- console.error(data.error)
- }else{
- alert("Fetching Data Failed.")
- console.error(data)
- }
- }else{
- alert("Fetching Data Failed.")
- console.error(data)
- }
- })
- .catch(error=>{
- console.log(error)
- alert("Fetching Data Failed.")
- })
- }
- /**
- * Delete Member
- * @param {*} $id
- * @returns
- */
- function delete_member($id=0){
- if(confirm(`Are you sure to delete this member?`) === false)
- return false;
- var formData = new FormData();
- formData.append('id', $id)
- fetch('api.php?action=delete_member',{
- method:'POST',
- body:formData
- })
- .then(resp => {
- return resp.json();
- })
- .then(data => {
- if(!!data.status){
- if(data.status == 'success'){
- alert("Member has been deleted successfully.");
- vanillaDT.destroy();
- vanillaDT.init();
- }else if(!!data.error){
- alert("Fetching Data Failed.")
- console.error(data.error)
- }else{
- alert("Fetching Data Failed.")
- console.error(data)
- }
- }else{
- alert("Fetching Data Failed.")
- console.error(data)
- }
- })
- .catch(error=>{
- console.log(error)
- alert("Fetching Data Failed.")
- })
- }
Snapshots
Using the provided snippets will result in a simple application that allows the end-user to manage the member list.
Main Page
Form Modal
That's it! You can now test the simple web application using the above snippets on your end. You can also download the compiled source code zip file on this website for free.
That's the end of this tutorial. I hope this Vanilla DataTables CRUD using PHP and MySQL Tutorial will help you with what you are looking for and that you'll find this useful for your future projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Comments
Add new comment
- Add new comment
- 2162 views