You are on page 1of 23

Source : https://seegatesite.

com/create-simple-crud-with-datatables-jquery-and-adminlte/
Table of Contents

Build CRUD PHP, MySQL, JQuery And AdminLTE in 10 Minutes (Bonus source
code) ...................................................................................................................... 3

Tutorial Create Simple CRUD APPLICATION Using PHP and Mysql ..................... 4

Requirements................................................................................................. 4

Create a database and table on MySQL.......................................................... 6

Create a new PHP CRUD project .................................................................... 7

CONCLUSION ................................................................................................... 22
Build CRUD PHP, MySQL, JQuery And AdminLTE in
10 Minutes (Bonus source code)

Create CRUD web applications (Create, Read, Update, and Delete) using PHP,
Jquery, and adminLTE is fast and efficient. The application of CRUD is the basis of
making information systems. So, you must be adept at implementing CRUD
specifically to learn PHP CRUD

Why?

If you master the PHP CRUD, you can quickly build dynamic websites.

On this occasion, I show you how to make a CRUD application using PHP and
JQuery. See the following tutorial
Here's the deal:

In this crud tutorial, you will learn several things, such as:

 How to create a table, add, edit and delete data on MySQL.

 How to use PHP PDO to communicate with the MySQL Database.

 Display database tables using Datatable.

 Using JQuery to interact with HTML and PHP services to update the MySQL
Database.

 Using the AdminLTE CSS Framework to create responsive mobile


applications.

 Understanding PHP MVC concept.

And as a bonus, you can download the PHP crud tutorial source code for free,
visit here to download the source code

https://seegatesite.com/create-simple-crud-with-datatables-jquery-and-adminlte/

Tutorial Create Simple CRUD APPLICATION Using PHP


and Mysql
To start the crud tutorial, you must prepare the several tools so that the
application runs smoothly.

Requirements
1. PHP

Must install PHP Server, to run this application you need PHP version 5 and above
(5.6 or PHP 7)

2. MySQL Database

the MySQL Database version that I used 5.7


3. AdminLTE CSS Framework.

Why do I use AdminLTE? I think adminLTE is the best free CSS framework
available today. Besides that, AdminLTE has an excellent layout and is very well
maintained.

Please download AdminLTE version 2.4 here https://adminlte.io.

4. Bootstrap Framework version 3

Because the adminLTE 2.4 uses bootstrap version 3, it automatically uses


bootstrap framework version 3

5. Datatables Plugins (already contained the adminLTE component)

Datatables is a table plugin for displaying the database tables with an interactive
interface and easy to use. Also, datatables supported the mobile display.

I will share the tutorial using datatables and JQuery to display data from the
server to the browser using AJAX so that the table looks more attractive.

6. JQuery Framework (already contained in adminlte)

The Jquery version used is adapted to the AdminLTE Framework version

7. SweetAlert plugin

SweetAlert plugin used to beautify the JavaScript alert box.

8. SQLYOG

An application that I used to updating and deleting the MySQL database. If you
don't have an SQLYog, you can use phpmyadmin or other database tools
Create a database and table on MySQL
 Create a database with the name "crud."

 Creating a customer table

 Add dummy data to the customer table


INSERT INTO customer(NAME,gender,country,phone) VALUES('Sigit Prasetya
N','Male','Indonesia','000-857489');

INSERT INTO customer(NAME,gender,country,phone) VALUES('Taylor


Swift','Female','United State','0858774858');

INSERT INTO customer(NAME,gender,country,phone) VALUES('Kristen


Stewart','Female','British','888-985859');
Create a new PHP CRUD project
- Create a new web applications project folder with the file names "crud" in your
public folder (if using xampp, put in the htdocs folder, for Ubuntu machine, set in
the folder /var/www/html/)

- Extracts adminlte.zip and copy bower_components, dist, plugins folder into


"crud" folder

- Install the sweetalert plugin using bower with the following code:

After installed, sweetalert plugin component added in the bower_components


folder.

- Create a new folder named "application" in the "crud" folder. "application"


folder used to put our crud apps file.

- Create a new folder (database and customer) and put in the "application" folder

Database folder
- Add 2 new file in the "database" folder with file names dbconn.php and sql.php

dbconn.php
dbconn.php used to record your database configuration using PDO. Add the
following code into dbconn.php:
<?php
class dbconn {
public $dblocal;
public function __construct()
{

}
public function initDBO()
{
$user = 'root';
$pwd = '';
$dbname = 'crud';
try {
$this->dblocal = new
PDO("mysql:host=localhost;dbname=".$dbname.";charset=latin1",$user,$pwd,array
(PDO::ATTR_PERSISTENT => true));
$this->dblocal-
>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die("Can't connect database");
}

}
?>

Explanation:

- PDO used to create connection between php and mysql.

- We created a new PHP class named "dbconn."

- PDO using try catch exception to create connection both of PHP and Database.
Using try-catch in PHP easier for us to maintain the error code.

- To connect the "crud" database tables, we use the following configuration.


Adjust the below code with your DB configuration

$user = 'root';
$pwd = '';
$dbname = 'crud';

sql.php
sql.php used as a model. The sql.php file contains a PHP class and list of PHP
functions used to keep the MySQL Query command. All queries related to the
database written in this class.

<?php
class sql extends dbconn {
public function __construct()
{
$this->initDBO();
}

public function new_customer($name,$country,$phone,$gender)


{
$db = $this->dblocal;
try
{
$stmt = $db->prepare("insert into
customer(name,country,phone,gender) values (:name,:country,:phone,:gender)");
$stmt->bindParam("name",$name);
$stmt->bindParam("country",$country);
$stmt->bindParam("phone",$phone);
$stmt->bindParam("gender",$gender);
$stmt->execute();
$stat[0] = true;
$stat[1] = "Success save customer";
return $stat;
}
catch(PDOException $ex)
{
$stat[0] = false;
$stat[1] = $ex->getMessage();
return $stat;
}
}

public function list_customer()


{
$db = $this->dblocal;
try
{
$stmt = $db->prepare("select * from customer");
$stmt->execute();
$stat[0] = true;
$stat[1] = "List customer";
$stat[2] = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $stat;
}
catch(PDOException $ex)
{
$stat[0] = false;
$stat[1] = $ex->getMessage();
$stat[2] = [];
return $stat;
}
}

public function edit_customer($id,$name,$country,$phone,$gender)


{
$db = $this->dblocal;
try
{
$stmt = $db->prepare("update customer set name = :name, country =
:country, phone = :phone , gender = :gender where id_cust = :id ");
$stmt->bindParam("id",$id);
$stmt->bindParam("name",$name);
$stmt->bindParam("country",$country);
$stmt->bindParam("phone",$phone);
$stmt->bindParam("gender",$gender);
$stmt->execute();
$stat[0] = true;
$stat[1] = "Success edit customer";
return $stat;
}
catch(PDOException $ex)
{
$stat[0] = false;
$stat[1] = $ex->getMessage();
return $stat;
}
}

public function delete_customer($id)


{
$db = $this->dblocal;
try
{
$stmt = $db->prepare("delete from customer where id_cust = :id");
$stmt->bindParam("id",$id);
$stmt->execute();
$stat[0] = true;
$stat[1] = "Success delete customer";
return $stat;
}
catch(PDOException $ex)
{
$stat[0] = false;
$stat[1] = $ex->getMessage();
return $stat;
}
}

Explanation:

- We created new php class named sql, sql class extend from dbconn class.

- We have 4 functions ( list_customer, new_customer, delete_customer,


edit_customer ) in sql class. This class used to create read update delete tables in
database.

- We created constructor function to call pdo configuration from dbconn class.

- list_customer used to read all data from crud table.


- We use 4 PDO object in this example to communicate with database ( $db-
>prepare, $stmt->execute() , $stmt->bindParam() , $stmt-
>fetchAll(PDO::FETCH_ASSOC) )

- $db->prepare

used to prepares a statement to execution and returns a PDO statement


object

- $stmt->execute()

used to execute prepared statement.

- $stmt->bindParam()

used to binding parameter into specified variable in prepare statement.

- $stmt->fetchAll(PDO::FETCH_ASSOC)

used to fetch all result set rows as an array

Until this step, you finished creating the business rule of your app. Next, we
generate front-end of the crud application

Customer folder
Create 2 files named customer.php and index.php. customer.php used as
controller. This controller will be the link between index.php as front-end and
sql.php as a database model

customer.php
Add the code below into customer.php
<?php

include "../database/dbconn.php";
include "../database/sql.php";
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && (
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
$method=$_POST['method'];
$dtbs = new sql();
$retval = [];
if($method == 'list_customer'){
$list = $dtbs->list_customer();
$retval['status'] = $list[0];
$retval['message'] = $list[1];
$retval['data'] = $list[2];
echo json_encode($retval);
}

if($method == 'new_customer'){
$name = $_POST['name'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$gender = $_POST['gender'];

$new = $dtbs->new_customer($name,$country,$phone,$gender);
$retval['status'] = $new[0];
$retval['message'] = $new[1];
echo json_encode($retval);
}

if($method == 'edit_customer'){
$id_cust = $_POST['id_cust'];
$name = $_POST['name'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$gender = $_POST['gender'];

$edit = $dtbs->edit_customer($id_cust,$name,$country,$phone,$gender);
$retval['status'] = $edit[0];
$retval['message'] = $edit[1];
echo json_encode($retval);
}

if($method == 'delete_customer'){
$id_cust = $_POST['id_cust'];
$delete = $dtbs->delete_customer($id_cust);
$retval['status'] = $delete[0];
$retval['message'] = $delete[1];
echo json_encode($retval);
}

}else{
header("HTTP/1.1 401 Unauthorized");
exit;
}

Explanation:

- To prevent Unauthorized access from the direct link to the customer.php file,
we can use the following code
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && (
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )

- We declared "sql" class object into a dtbs variable. The dtbs variable used to call
the database controller that we created before.

- To divide the code into sections ( function to show list customer, to add new
customer, edit and delete customer), I used $_POST['method'] using specified
string value.

- Cause we use JQuery ajax to call the function, we need to return the result with
"echo" function. The array result transformed into a json string using the
json_encode method

index.php
index.php used as a front-end layout of these apps. Also, all of the JQuery code to
doing the CRUD function will be set in this file.

To more comfortable using the adminlte template, we can copy the whole code
from their blank template, blank.html. The blank.html located in the adminlte
source code folder (/pages/example/blank.html).

After copied these code, we first add the sweetalert and datatables plugin into
index.php. Add the sweetalert and datatables CSS code before </head> element.
look the following code
<link rel="stylesheet" href="../../bower_components/bootstrap-
sweetalert/dist/sweetalert.css">
<link rel="stylesheet" href="../../bower_components/datatables.net-
bs/css/dataTables.bootstrap.css">
Then, copy the code below to add sweetalert and datatables js file before
</body> element.
<script src="../../bower_components/bootstrap-
sweetalert/dist/sweetalert.min.js"></script>
<script
src="../../bower_components/datatables.net/js/jquery.dataTables.min.js"></scr
ipt>
<script src="../../bower_components/datatables.net-
bs/js/dataTables.bootstrap.js"></script>

Add the html code below into element <div class="content-wrapper">


<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
TUTORIAL PHP CRUD
<small>visit <a
href="https://seegatesite.com">seegatesite.com</a> for more tutorial</small>
</h1>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-body">
<button class="btn btn-primary margin" id="btn-add"
title="New button"><i class="fa fa-plus"></i> New Customer</button>
<div class="table-responsive margin">
<table id="table-customer" class="table table-
bordered">
<thead>
<tr>
<th style="width: 10px">#</th>
<th style="width: 150px">Name</th>
<th style="width: 50px">Gender</th>
<th style="width: 50px">Country</th>
<th style="width: 25px;">Phone</th>
<th style="width: 50px;"></th>
</tr>
</thead>
</table>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Modal -->
<div class="modal fade" id="modal-customer" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Form
Customer</h4>
</div>
<div class="modal-body">
<div class="box-body">
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-
label">Name</label>
<div class="col-sm-9">
<input type="hidden" id="crud">
<input type="hidden" id="txtcode">
<input type="text" class="form-control"
id="txtname" placeholder="Customer Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-
label">Gender</label>
<div class="col-sm-9">
<select class="form-control"
id="cbogender">
<option value="Male">Male</option>
<option
value="Female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-
label">Country</label>
<div class="col-sm-9">
<input type="text" class="form-control"
id="txtcountry" placeholder="Country Name">
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-
label">Phone</label>
<div class="col-sm-9">
<input type="text" class="form-control"
id="txtphone" placeholder="phone number">
</div>
</div>

</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" title="save
button" id="btn-save"> <i class="fa fa-save"></i> Save</button>
</div>
</div>
</div>
</div>

Make sure the application layout like the following image:

Add the javascript code before </body> element


<script type="text/javascript">
$(document).ready(function(){

// function to repair keyboard tab in modal dialog adminlte


(function (){
var close = window.swal.close;
var previousWindowKeyDown = window.onkeydown;
window.swal.close = function() {
close();
window.onkeydown = previousWindowKeyDown;
};
})();

$('#table-customer').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"processing": true,
"ordering": false,
"info": false,
"responsive": true,
"autoWidth": false,
"pageLength": 100,
"dom": '<"top"f>rtip',
"fnDrawCallback": function( oSettings ) {
},
"ajax": {
"url": "customer.php",
"type": "POST",
"data" : {
method : "list_customer"
},
error: function (request, textStatus, errorThrown) {
swal(request.responseJSON.message);
}
},

columns: [
{ "data": null,render : function ( data, type, full, meta )
{
return meta.row + 1;
}},
{ "data": "name" },
{ "data": "gender" },
{ "data": "country" },
{ "data": "phone" },
{ "data": null, render : function(data,type,row){
return "<button title='Edit' class='btn btn-edit btn-
warning btn-xs'><i class='fa fa-pencil'></i> Edit</button> <button
title='Delete' class='btn btn-hapus btn-danger btn-xs'><i class='fa fa-
remove'></i> Delete</button> ";
} },
]
});

$("#btn-save").click(function(){
if($("#txtname").val() == ''){
swal("Please enter name");
return;
}
if($("#txtcountry").val() == ''){
swal("Please enter country");
return;
}
if($("#txtphone").val() == ''){
swal("PLease enter contact number");
return;
}

if($("#crud").val() == 'N'){
swal({
title: "New",
text: "Create new customer ?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-primary",
confirmButtonText: "Save",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){

add_customer($("#txtname").val(),$("#txtcountry").val(),$("#cbogender").val()
,$("#txtphone").val());
});
}else{
swal({
title: "Edit",
text: "Edit customer ?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-primary",
confirmButtonText: "Update",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){

edit_customer($("#txtcode").val(),$("#txtname").val(),$("#txtcountry").val(),
$("#cbogender").val(),$("#txtphone").val());

});
}
});

$("#btn-add").click(function(){
$("#modal-customer").modal("show");
$("#txtname").val("");
$("#txtcountry").val("");
$("#txtphone").val("");
$("#crud").val("N");
});
});

$(document).on("click",".btn-edit",function(){
var current_row = $(this).parents('tr');
if (current_row.hasClass('child')) {
current_row = current_row.prev();
}
var table = $('#table-customer').DataTable();
var data = table.row( current_row).data();
$("#txtname").val(data.name);
$("#txtcode").val(data.id_cust);
$("#txtcountry").val(data.country);
$("#cbogender").val(data.gender)
$("#txtphone").val(data.phone)
$("#modal-customer").modal("show");
setTimeout(function(){
$("#txtname").focus()
}, 1000);

$("#crud").val("E");

});

$(document).on("click",".btn-hapus",function(){
let current_row = $(this).parents('tr');
if (current_row.hasClass('child')) {
current_row = current_row.prev();
}
let table = $('#table-customer').DataTable();
let data = table.row( current_row).data();
let idcust = data.id_cust;
swal({
title: "Delete",
text: "Delete customer ?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Delete",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){

let ajax = {
method : "delete_customer",
id_cust : idcust,
}
$.ajax({
url:"customer.php",
type: "POST",
data: ajax,
success: function(data, textStatus, jqXHR)
{
$resp = JSON.parse(data);
if($resp['status'] == true){
swal("Success delete customer");
let xtable = $('#table-customer').DataTable();
xtable.ajax.reload( null, false );
}else{
swal("Error delete customer : "+$resp['message'])
}

},
error: function (request, textStatus, errorThrown) {
swal("Error ", request.responseJSON.message,
"error");
}
});
});
});
function add_customer(nm,ctr,gdr,phn){
let ajax = {
method: "new_customer",
name : nm,
country:ctr,
gender:gdr,
phone:phn

}
$.ajax({
url: "customer.php",
type: "POST",
data: ajax,
success: function(data, textStatus, jqXHR)
{
$resp = JSON.parse(data);
if($resp['status'] == true){
$("#txtname").val("");
$("#txtcountry").val("");
$("#txtphone").val("");
$("#txtcode").val("");
$("#txtcode").focus();
let xtable = $('#table-customer').DataTable();
xtable.ajax.reload( null, false );
swal("Success save new customer");
}else{
swal("Error save customer : "+$resp['message'])
}
},
error: function (request, textStatus, errorThrown) {
swal("Error ", request.responseJSON.message, "error");
}
});
}

function edit_customer(id,nm,ctr,gdr,phn){
let ajax = {
method: "edit_customer",
id_cust : id,
name : nm,
country:ctr,
gender:gdr,
phone:phn

}
$.ajax({
url: "customer.php",
type: "POST",
data: ajax,
success: function(data, textStatus, jqXHR)
{
$resp = JSON.parse(data);

if($resp['status'] == true){
$("#modal-customer").modal("hide");
swal("Success edit customer ");
let xtable = $('#table-customer').DataTable();
xtable.ajax.reload( null, false );
}else{
swal("Error save customer : "+$resp['message'])
}
},
error: function (request, textStatus, errorThrown) {
swal("Error ", request.responseJSON.message, "error");

}
});
}
</script>

Explanation:

- We used $(document).ready() to execute all jquery code when the page is fully
loaded.

- The below function used to resolve modal dialog adminLTE when using the
sweetalert plugin. There are bugs in modal dialog bootstrap and sweetalert
plugin. The keyboard tab does not work correctly after sweetalert API fired. I
already discussed in the article [Resolved] SweetAlert Prompt Not Working On
Modal Dialog Bootstrap In Firefox

- To declare datatables plugin we call $('#table-customer').DataTable({}) method


with some parameter. Datatables load all customer data dynamically using ajax.

- I create 2 javascript functions to make new customer and update customer data
(add_customer and edit_customer).

- Using jQuery.ajax() to perform HTTP request without loading a page (this is one
of the advantage using jQuery, speed up writing code to use the HTTP request
function in Javascript). Ajax() method send a data object. Each object has a
property named "method" who have a specific value to call the function on the
controller file (customer.php)

- To parse the data from the web server, we use JSON.parse function. When
exchange data from a web server, the data is always a string. We transform the
json string into a json object. Since JQuery 3 version, don't use jQuery.parseJSON
again because it's deprecated.

Until this step, you successfully create PHP crud application. Run from the
browser "http://localhost/crud/application/customer/" and your application must
be like the following image.

DEMO : https://www.youtube.com/watch?v=wwsqbjm8Mto

CONCLUSION
- You learned the simplest MVC concept from the example PHP crud above. The
advantage is you easily understand the workflow of the PHP framework when
learning laravel and codeigniter.

- You learned the PDO concept in PHP. The advantage is you not to worry when
upgrading your PHP version from PHP 5 to PHP 7. Because, mysql_connect()
function deprecated in PHP 7. PDO class more secure and more effective when
maintaining database connection. Besides, you implemented and learned how to
use OOP technique in PHP when creating dbconn dan sql class.

- You learned how to use adminlte framework template in your application.

- Using JQuery to create a to-do list app relatively easier and fast without
refreshing the page.

This is my article about the PHP crud tutorial. With 10 minutes, you have
mastered the real concept of crud application. Hopefully useful

Best Regard

Sigit Prasetya Nugroho

You might also like