Professional Documents
Culture Documents
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
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:
Using JQuery to interact with HTML and PHP services to update the MySQL
Database.
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/
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
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.
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.
7. SweetAlert plugin
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."
- Install the sweetalert plugin using bower with the following code:
- 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 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.
$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();
}
Explanation:
- We created new php class named sql, sql class extend from dbconn class.
- $db->prepare
- $stmt->execute()
- $stmt->bindParam()
- $stmt->fetchAll(PDO::FETCH_ASSOC)
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>
<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>
$('#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
- 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.
- 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