Saturday 7 January 2017

PHP PDO CRUD with Ajax Jquery and Bootstrap



This is one more post on How to create Crud system in PHP Language. But in this post we have make Crud System in PHP by using PHP PDO Modal class with Ajax Jquery with Bootstrap. In this system we have use Ajax JQuery method with PHP PDO modal, so we can perform all CRUD operation like Create, Read, Update and Delete on single page event without refresh of page.

We have already make this type of Crud system by using Simple PHP Object Oriented Programming and we have also make Crud system in Codeigniter Framework also. But now we have use PHP PDO Modal class for making this Crud system in PHP. 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>How to Read Mysql Data by using PHP PDO with Ajax - PHP PDO CRUD with Ajax</title>
  <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>
  <style>
   body
   {
    margin:0;
    padding:0;
    background-color:#f1f1f1;
   }
   .box
   {
    width:1270px;
    padding:20px;
    background-color:#fff;
    border:1px solid #ccc;
    border-radius:5px;
    margin-top:100px;
   }
  </style>
 </head>
 <body>
  <div class="container box">
   <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>
 </body>
</html>

<!-- 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" />
    <br />
    <label>Enter Last Name</label>
    <input type="text" name="last_name" id="last_name" class="form-control" />
    <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>

<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", //Request send to "action.php page"
   method:"POST", //Using of Post method for send data
   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(''); //This will clear Modal first name textbox
  $('#last_name').val(''); //This will clear Modal last name textbox
  $('.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>
 

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 .= '
   <table class="table table-bordered">
    <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><button type="button" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button></td>
     <td><button type="button" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td align="center">Data not Found</td>
    </tr>
   ';
  }
  $output .= '</table>';
  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';
  }
 }

}

?>
 

Database


 
 --
-- Database: `crud`
--

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

--
-- Table structure for table `customers`
--

CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`id`, `first_name`, `last_name`) VALUES
(18, 'Joseph', 'Harman'),
(19, 'John', 'Moss'),
(20, 'Lillie', 'Ferrarium'),
(21, 'Yolanda', 'Green'),
(22, 'Cara', 'Gariepy'),
(55, 'Opal', 'Goree'),
(23, 'Christine', 'Johnson'),
(24, 'Alana', 'Decruze'),
(25, 'Krista', 'Correa'),
(26, 'Charles', 'Martin'),
(54, 'Rhonda', 'Ocampo'),
(51, 'Cecilia', 'Roy'),
(52, 'Otto', 'Estes'),
(53, 'Richardson', 'Fishback'),
(56, 'Rudy', 'Buckley');
 

11 comments:

  1. Merci et milles merci de partager ce formidable code qui résume merveilleusement tout ce qu'un développeur débutant est censé apprendre c'est un bijoux

    ReplyDelete
  2. I liked the code, but in the part of the listing could structure the table in the index and the file action.php would only put the << th >> and their respective value

    ReplyDelete
  3. Thanks for this great tutorial! It works as it is, however, when I try to add tables beside the first and lastname and modify the mysql table accordingly I end up dont seeing any data in the index.php div with id result. I tried to modify every instance in the code where I had tp enter the extra tablenames and form ids. Can you please help me?

    ReplyDelete
  4. gr8t tutorial but how can i download it?

    ReplyDelete
  5. Hello,

    very nice tutorial! I have a question: How can i use a dropdown list to select options? Updating using drop down list is no problem, but adding new data doesn't works... May you can help me to solve this problem (i am a absolute beginner) Kind regards, Daniel

    ReplyDelete
  6. Hello,

    very nice tutorial! I have a question: How can i use a dropdown list to select options? Updating is no problem, but adding new data doesn't works. May you can help me (i am an absolute beginner). Kind regards, Daniel

    ReplyDelete
  7. hi sir
    my project shop invantory

    please help me conection into jquery phpmysqli

    my customer form fetch and edit customer form data fetch reomve etc

    i have allredy send my project in your mailid please chech and ccorrection

    ReplyDelete
  8. First Thank's for this exemple, then i have a problem, i wish that i have some help,
    I use this exemple for my work and when i add records for first time it's work after that is never work, i can create records just for one time.
    and if i delete the records created i can add another one i can all time add one records

    ReplyDelete
  9. Thank you for the code! Please update to the latest bootstrap, jquery etc...

    ReplyDelete
  10. c'est le post le plus important qui ma fait avancer merci bbeaucoup

    ReplyDelete
  11. great! tks so much! In a beautiful Brazilian Portuguese: valeu mano!

    ReplyDelete