FB Youtube Twitter

PHP MySQL CRUD Operations using jQuery and Bootstrap

Ashraf Ali S

What is CRUD

CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation for database. We’ve already learned how to perform create (i.e. insert), read (i.e. select), update and delete operations in previous chapters. In this tutorial we’ll create a simple PHP application to perform all these operations on a MySQL database table at one place.

Well, let’s start by creating the table which we’ll use in all of our example.

Creating the Database Table

Execute the following SQL query to create a table named employees inside your MySQL database. We will use this table for all of our future operations.

--
-- Database:`crud`
--
-- ------ Table structure for table `customers` --
CREATE TABLE IF NOT EXISTS `customers` ( `id` int(11) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL ) ENGINE=MyISAM AUTO_INCREMENT=81 DEFAULT CHARSET=latin1;
-- -- Indexes for dumped tables -- -- -- Indexes for table `customers` --
ALTER TABLE `customers` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `customers` -- ALTER TABLE `customers` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=81;

There are many benefits of using PHP PDO for our web development projects. Following are the benefits of using PHP PDO.

  • It is an Object Oriented.
  • Bind parameters in statements.
  • Allows for prepared statements and rollback functionality
  • Throws catch able exceptions for better error handling.. and many more

If you have use PHP PDO in your project, then you can use different databases with same code, you have not re-write new code for different database engine. You can use same code for your system operation like Insert, Update, Delete and Fetch data from database in PHP.

In this tutorial you can find how to Insert or Add data, Update or Edit Data, Delete or remove data and Select or Fetch data from database by using PHP PDO with Ajax JQuery. You can find Source source code for how to perform this crud operation in PHP PDO with JQuery Ajax method. By using this source code you can make single page CRUD application by using PHP PDO with Ajax JQuery.

Source Code

index.php

<html>
 <head>
  <title>PHP PDO CRUD with Ajax - Create Read Update Data</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script>
  $(document).ready(function(){
   fetchUser(); //This function will load all data on web page when page load
   function fetchUser() // This function will fetch data from table and display under <div id="result">
   {
    var action = "Load";
    $.ajax({
     url : "action.php",
     method:"POST",
     data:{action:action}, //action variable data has been send to server
     success:function(data){
      $('#result').html(data); //It will display data under div tag with id result
     }
    });
   }

   //This JQuery code will Reset value of Modal item when modal will load for create new records
   $('#modal_button').click(function(){
    $('#customerModal').modal('show'); //It will load modal on web page
    $('#first_name').val('');
    $('#last_name').val('');
    $('.modal-title').text("Create New Records"); //It will change Modal title to Create new Records
    $('#action').val('Create'); //This will reset Button value ot Create
   });

   //This JQuery code is for Click on Modal action button for Create new records or Update existing records. This code will use for both Create and Update of data through modal
   $('#action').click(function(){
    var firstName = $('#first_name').val(); //Get the value of first name textbox.
    var lastName = $('#last_name').val(); //Get the value of last name textbox
    var id = $('#customer_id').val();  //Get the value of hidden field customer id
    var action = $('#action').val();  //Get the value of Modal Action button and stored into action variable
    if(firstName != '' && lastName != '') //This condition will check both variable has some value
    {
     $.ajax({
      url : "action.php",    //Request send to "action.php page"
      method:"POST",     //Using of Post method for send data
      data:{firstName:firstName, lastName:lastName, id:id, action:action}, //Send data to server
      success:function(data){
       alert(data);    //It will pop up which data it was received from server side
       $('#customerModal').modal('hide'); //It will hide Customer Modal from webpage.
       fetchUser();    // Fetch User function has been called and it will load data under divison tag with id result
      }
     });
    }
    else
    {
     alert("Both Fields are Required"); //If both or any one of the variable has no value them it will display this message
    }
   });

   //This JQuery code is for Update customer data. If we have click on any customer row update button then this code will execute
   $(document).on('click', '.update', function(){
    var id = $(this).attr("id"); //This code will fetch any customer id from attribute id with help of attr() JQuery method
    var action = "Select";   //We have define action variable value is equal to select
    $.ajax({
     url:"action.php",   //Request send to "action.php page"
     method:"POST",    //Using of Post method for send data
     data:{id:id, action:action},//Send data to server
     dataType:"json",   //Here we have define json data type, so server will send data in json format.
     success:function(data){
      $('#customerModal').modal('show');   //It will display modal on webpage
      $('.modal-title').text("Update Records"); //This code will change this class text to Update records
      $('#action').val("Update");     //This code will change Button value to Update
      $('#customer_id').val(id);     //It will define value of id variable to this customer id hidden field
      $('#first_name').val(data.first_name);  //It will assign value to modal first name texbox
      $('#last_name').val(data.last_name);  //It will assign value of modal last name textbox
     }
    });
   });

   //This JQuery code is for Delete customer data. If we have click on any customer row delete button then this code will execute
   $(document).on('click', '.delete', function(){
    var id = $(this).attr("id"); //This code will fetch any customer id from attribute id with help of attr() JQuery method
    if(confirm("Are you sure you want to remove this data?")) //Confim Box if OK then
    {
     var action = "Delete"; //Define action variable value Delete
     $.ajax({
      url:"action.php",    //Request send to "action.php page"
      method:"POST",     //Using of Post method for send data
      data:{id:id, action:action}, //Data send to server from ajax method
      success:function(data)
      {
       fetchUser();    // fetchUser() function has been called and it will load data under divison tag with id result
       alert(data);    //It will pop up which data it was received from server side
      }
     })
    }
    else  //Confim Box if cancel then
    {
     return false; //No action will perform
    }
   });
  });
  </script>

 </head>
 <body>
  <div class="container">
   <h1 align="center">PHP PDO CRUD with Ajax Jquery and Bootstrap</h1>
   <br />
   <div align="right">
    <button type="button" id="modal_button" class="btn btn-info">Create Records</button>
    <!-- It will show Modal for Create new Records !-->
   </div>
   <br />
   <div id="result" class="table-responsive"> <!-- Data will load under this tag!-->

   </div>
  </div>
  <!-- This is Customer Modal. It will be use for Create new Records and Update Existing Records!-->
  <div id="customerModal" class="modal fade">
   <div class="modal-dialog">
    <div class="modal-content">
     <div class="modal-header">
      <h4 class="modal-title">Create New Records</h4>
     </div>
     <div class="modal-body">
      <label>Enter First Name</label>
      <input type="text" name="first_name" id="first_name" class="form-control"  pattern="[A-Za-z]{1,15}" />
      <br />
      <label>Enter Last Name</label>
      <input type="text" name="last_name" id="last_name" class="form-control"  pattern="[0-9]{10}"/>
      <br />
     </div>
     <div class="modal-footer">
      <input type="hidden" name="customer_id" id="customer_id" />
      <input type="submit" name="action" id="action" class="btn btn-success" />
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
     </div>
    </div>
   </div>
  </div>

 </body>
</html>

action.php

<?php
//Database connection by using PHP PDO
$username = 'root';
$password = '';
$connection = new PDO( 'mysql:host=localhost;dbname=crud', $username, $password ); // Create Object of PDO class by connecting to Mysql database

if(isset($_POST["action"])) //Check value of $_POST["action"] variable value is set to not
{
 //For Load All Data
 if($_POST["action"] == "Load")
 {
  $statement = $connection->prepare("SELECT * FROM customers ORDER BY id DESC");
  $statement->execute();
  $result = $statement->fetchAll();
  $output = '';
  $output .= '
  <div class="table-responsive">
   <table class="table table-bordered table-hover">
    <tr>
     <th width="40%">First Name</th>
     <th width="40%">Last Name</th>
     <th width="10%">Update</th>
     <th width="10%">Delete</th>
    </tr>
  ';
  if($statement->rowCount() > 0)
  {
   foreach($result as $row)
   {
    $output .= '
    <tr>
     <td>'.$row["first_name"].'</td>
     <td>'.$row["last_name"].'</td>
     <td><center><button type="button" id="'.$row["id"].'" class="btn btn-warning update">Update</button></center></td>
     <td><center><button type="button" id="'.$row["id"].'" class="btn btn-danger delete">Delete</button></center></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td align="center">Data not Found</td>
    </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }

 //This code for Create new Records
 if($_POST["action"] == "Create")
 {
  $statement = $connection->prepare("
   INSERT INTO customers (first_name, last_name)
   VALUES (:first_name, :last_name)
  ");
  $result = $statement->execute(
   array(
    ':first_name' => $_POST["firstName"],
    ':last_name' => $_POST["lastName"]
   )
  );
  if(!empty($result))
  {
   echo 'Data Inserted';
  }
 }

 //This Code is for fetch single customer data for display on Modal
 if($_POST["action"] == "Select")
 {
  $output = array();
  $statement = $connection->prepare(
   "SELECT * FROM customers
   WHERE id = '".$_POST["id"]."'
   LIMIT 1"
  );
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output["first_name"] = $row["first_name"];
   $output["last_name"] = $row["last_name"];
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "Update")
 {
  $statement = $connection->prepare(
   "UPDATE customers
   SET first_name = :first_name, last_name = :last_name
   WHERE id = :id
   "
  );
  $result = $statement->execute(
   array(
    ':first_name' => $_POST["firstName"],
    ':last_name' => $_POST["lastName"],
    ':id'   => $_POST["id"]
   )
  );
  if(!empty($result))
  {
   echo 'Data Updated';
  }
 }

 if($_POST["action"] == "Delete")
 {
  $statement = $connection->prepare(
   "DELETE FROM customers WHERE id = :id"
  );
  $result = $statement->execute(
   array(
    ':id' => $_POST["id"]
   )
  );
  if(!empty($result))
  {
   echo 'Data Deleted';
  }
 }

}

?>

DEMO
[sociallocker]

DOWNLOAD
[/sociallocker]


3 Comments

Ganesh y · 30th September 2018 at 7:03 pm

Nice bro

George Marantis · 8th January 2019 at 3:07 pm

I’ll give it a try

ergfir nolikz · 10th January 2019 at 3:51 am

Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is magnificent blog. An excellent read. I’ll definitely be back.

Leave a Reply

Your email address will not be published. Required fields are marked *