PHP - Simple CRUD With Ajax/MySQLi

In this tutorial we will create a Simple CRUD With Ajax/MySQLi using PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by a newly coders for its user friendly environment. Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page. So Let's do the coding.

Before we started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/

Creating Database

Open your database web server then create a database name in it db_crud, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepadd++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'db_crud');
  3.  
  4. if(!$conn){
  5. die("Error: Cannot connect to the database");
  6. }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as shown below. index.php.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Simple CRUD With Ajax/MySQLi</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <form method="POST">
  18. <div class="form-inline">
  19. <label>Firstname</label>
  20. <input type="text" id="firstname" class="form-control"/>
  21. <label>Lastname</label>
  22. <input type="text" id="lastname" class="form-control"/>
  23. </div>
  24. <br />
  25. <div class="form-inline">
  26. <label>Address</label>
  27. <input type="text" id="address" class="form-control"/>
  28. </div>
  29. <br />
  30. <center><button type="button" id="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button><button type="button" id="update" class="btn btn-warning"><span class="glyphicon glyphicon-edit"></span> Update</button></center>
  31. </form>
  32. <br />
  33. <table class="table table-bordered">
  34. <thead>
  35. <tr>
  36. <th>Name</th>
  37. <th>Address</th>
  38. <th>Action</th>
  39. </tr>
  40. </thead>
  41. <tbody id="data"></tbody>
  42. </table>
  43. </div>
  44. </body>
  45. <script src="js/jquery-3.2.1.min.js"></script>
  46. <script src="js/script.js"></script>
  47. </html>

Creating The Queries

This code contains the main function of the application. This code contains a different functionalities that needed to make this application work. This include the Create, Read, Update, Delete functionalities that will be called via the ajax method. To do that copy and write these block of codes inside your text editor, then save it as shown below. save_query.php This code will save the data input to the database server. This will process all the data then will be manage by the ajax request.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. $firstname = $_POST['firstname'];
  5. $lastname = $_POST['lastname'];
  6. $address = $_POST['address'];
  7.  
  8. $conn->query("INSERT INTO `member` VALUES('', '$firstname', '$lastname', '$address')");
  9. ?>
data_query.php This code will display the data from the database. This will render the data from the database via ajax request.
  1. <?php
  2. require_once 'conn.php';
  3. if(ISSET($_POST['res'])){
  4. $query = $conn->query("SELECT * FROM `member`");
  5. while($fetch = $query->fetch_array()){
  6. echo
  7. "
  8. <tr>
  9. <td>".$fetch['firstname']." ".$fetch['lastname']."</td>
  10. <td>".$fetch['address']."</td>
  11. <td><center><button class='btn btn-warning edit' name='".$fetch['mem_id']."'><span class='glyphicon glyphicon-edit'></span> Edit</button> | <button class='btn btn-danger delete' name='".$fetch['mem_id']."'><span class='glyphicon glyphicon-trash'></span> Delete</button></center></td>
  12. </tr>
  13. ";
  14.  
  15. }
  16. }
  17.  
  18. ?>
delete_query,php This code will delete the data from the database. This will delete the record from database when the target button is clicked.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. $id = $_POST['id'];
  5.  
  6. $conn->query("DELETE FROM `member` WHERE `mem_id` = '$id'");
  7. ?>
edit.php This code will display the data from the database base on the click row data. This will populate the inputs based on the row that has been clicked.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['id'])){
  5. $id = $_POST['id'];
  6.  
  7. $query = $conn->query("SELECT * FROM `member` WHERE `mem_id` ='$id'");
  8. $fetch = $query->fetch_array();
  9.  
  10. $array = array(
  11. 'mem_id' => $fetch['mem_id'],
  12. 'firstname' => $fetch['firstname'],
  13. 'lastname' => $fetch['lastname'],
  14. 'address' => $fetch['address']
  15. );
  16.  
  17. echo json_encode($array);
  18. }
  19. ?>
update_query.php This code will update the data from the database base on the click row data. This will checked and update the data from the database based on the selected row data.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['id'])){
  5. $id = $_POST['id'];
  6. $firstname = $_POST['firstname'];
  7. $lastname = $_POST['lastname'];
  8. $address = $_POST['address'];
  9.  
  10. $conn->query("UPDATE `member` set `firstname` = '$firstname', `lastname` = '$lastname', `address` = '$address' WHERE `mem_id` = '$id'");
  11. }
  12.  
  13. ?>

Creating The Ajax Funcition

This is where the code that uses ajax script. This code contains a different functionalities that manage the php queries to be able to send some information to the database. To do that just simply copy and write these block of codes inside the text editor, then save it as script.js inside the js folder.
  1. $(document).ready(function(){
  2. var mem_id;
  3.  
  4. DisplayData();
  5.  
  6. $('#update').hide();
  7.  
  8. $('#save').on('click', function(){
  9. if($('#firstname').val() == "" || $('#lastname').val() == "" || $('#address').val() == ""){
  10. alert("Hello World");
  11. }else{
  12. var firstname = $('#firstname').val();
  13. var lastname = $('#lastname').val();
  14. var address = $('#address').val();
  15.  
  16. $.ajax({
  17. url: 'save_query.php',
  18. type: 'POST',
  19. data: {
  20. firstname: firstname,
  21. lastname: lastname,
  22. address: address
  23. },
  24. success: function(data){
  25. $('#firstname').val('');
  26. $('#lastname').val('');
  27. $('#address').val('');
  28. DisplayData();
  29. }
  30. });
  31. }
  32.  
  33. });
  34.  
  35. function DisplayData(){
  36. $.ajax({
  37. url: 'data_query.php',
  38. type: 'POST',
  39. data: {
  40. res: 1
  41. },
  42. success: function(response){
  43. $('#data').html(response);
  44. }
  45. })
  46. }
  47.  
  48. $(document).on('click', '.delete', function(){
  49. var id = $(this).attr('name');
  50.  
  51. $.ajax({
  52. url: 'delete_query.php',
  53. type: 'POST',
  54. data: {
  55. id: id
  56. },
  57. success: function(data){
  58. DisplayData();
  59. $('#update').hide();
  60. $('#save').show();
  61. $('#firstname').val('');
  62. $('#lastname').val('');
  63. $('#address').val('');
  64. }
  65. });
  66. })
  67.  
  68. $(document).on('click', '.edit', function(){
  69. var id = $(this).attr('name');
  70.  
  71. $.ajax({
  72. url: 'edit.php',
  73. type: 'POST',
  74. data: {
  75. id: id
  76. },
  77. success: function(response){
  78. var getArray = jQuery.parseJSON(response);
  79.  
  80. mem_id = getArray.mem_id;
  81.  
  82. $('#firstname').val(getArray.firstname);
  83. $('#lastname').val(getArray.lastname);
  84. $('#address').val(getArray.address);
  85.  
  86. $('#update').show();
  87. $('#save').hide();
  88. }
  89. })
  90. });
  91.  
  92. $('#update').on('click', function(){
  93. var firstname = $('#firstname').val();
  94. var lastname = $('#lastname').val();
  95. var address = $('#address').val();
  96.  
  97.  
  98. $.ajax({
  99. url: 'update_query.php',
  100. type: 'POST',
  101. data: {
  102. id: mem_id,
  103. firstname: firstname,
  104. lastname: lastname,
  105. address: address
  106. },
  107. success: function(){
  108. DisplayData();
  109. $('#firstname').val('');
  110. $('#lastname').val('');
  111. $('#address').val('');
  112.  
  113. alert("Successfully Updated!");
  114.  
  115. $('#update').hide();
  116. $('#save').show();
  117.  
  118. mem_id = "";
  119. }
  120. });
  121. });
  122. });
There you have it we successfully created a Simple CRUD With Ajax/MySQLi using PHP. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Comments

Add new comment