PHP MySQL Ajax Add Edit Delete on Same Page

Hello PHP programmers and developers, php mysql add edit delete same page. Here, i will show you how to add/insert, edit, update and delete on same page in PHP MySQL using jQuery ajax.

In this php mysql add edit delete same page example tutorial, i will use bootstrap model to add and edit data from mysql database using jQuery ajax.

Also, you can use this code personally and professionally.

How to Add Edit Delete on Same Page in PHP MySQL Ajax

Let’s follow following easy steps to add edit delete on same page from database in PHP MySQL using jQuery ajax:

  • Step 1 – Create PHP Project
  • Step 2 – Create phpmyadmin MySQL Database and Connecting File
  • Step 3 – Create Index.php
  • Step 4 – Create add-update.php
  • Step 5 – Create edit.php
  • Step 5 – Create delete.php

Step 1 – Create PHP Project

In step 1, Navigate to your local web server directory. And inside this directory, create one directory. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 2 – Create phpmyadmin MySQL Database and Connecting File

In step 2, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `customers` (
  `id` int(10) UNSIGNED NOT NULL,
  `fname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `lname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Then create a php file that named mydbCon. Which is used to connect phpmyadmin mysql database to project (demo).

So, now create mydbCon file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $dbCon = mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$dbCon){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 3 – Create Index.php

In step 3, create a php file that named index.php. This file will display records from MySQL database.

And also, i will use jQuery ajax code for add edit delete on index.php file.

So, you need to add the following ajax html form code into index.php file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP MySQL Add Edit Delete Same Page</title>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container mt-2">

    <div class="row">
      <div class="col-md-8 mt-1 mb-1"><h2 class="text-white bg-dark">PHP MySQL Add Edit Delete Same Page</h2></div>
        <div class="col-md-8 mt-1 mb-2"><button type="button" id="create" class="btn btn-success">Add</button></div>
        <div class="col-md-8">
            <table class="table">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">First</th>
                  <th scope="col">Last</th>
                  <th scope="col">Email</th>
                  <th scope="col">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php

                include 'mydbCon.php';

                $query="select * from customers limit 200"; // Fetch all the data from the table customers

                $result=mysqli_query($dbCon,$query);

                ?>

                <?php if ($result->num_rows > 0): ?>

                <?php while($array=mysqli_fetch_row($result)): ?>

                <tr>
                    <th scope="row"><?php echo $array[0];?></th>
                    <td><?php echo $array[1];?></td>
                    <td><?php echo $array[2];?></td>
                    <td><?php echo $array[3];?></td>
                    <td> 
                      <a href="javascript:void(0)" class="btn btn-primary edit" data-id="<?php echo $array[0];?>">Edit</a>
                      <a href="javascript:void(0)" class="btn btn-primary delete" data-id="<?php echo $array[0];?>">Delete</a>
                </tr>

                <?php endwhile; ?>

                <?php else: ?>
                <tr>
                   <td colspan="3" rowspan="1" headers="">No Data Found</td>
                </tr>
                <?php endif; ?>

                <?php mysqli_free_result($result); ?>

              </tbody>
            </table>
        </div>
    </div>        
</div>

<!-- boostrap model -->
    <div class="modal fade" id="ajax-modal" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="custCrudModal"></h4>
          </div>
          <div class="modal-body">
            <form action="javascript:void(0)" id="custForm" name="custForm" class="form-horizontal" method="POST">
              <input type="hidden" name="custId" id="custId">
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">First Name</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="fname" name="fname" placeholder="Enter Name" value="" maxlength="50" required="">
                </div>
              </div>  

              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Last Name</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Enter Name" value="" maxlength="50" required="">
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">Email</label>
                <div class="col-sm-12">
                  <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" value="" required="">
                </div>
              </div>

              <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes
                </button>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            
          </div>
        </div>
      </div>
    </div>
<!-- end bootstrap model -->
<script type="text/javascript">
 $(document).ready(function($){

    $('#create').click(function () {
       $('#custForm').trigger("reset");
       $('#custCrudModal').html("Add New Customer");
       $('#ajax-modal').modal('show');
    });
 
    $('body').on('click', '.edit', function () {

        var id = $(this).data('id');
         
        // ajax
        $.ajax({
            type:"POST",
            url: "edit.php",
            data: { id: id },
            dataType: 'json',
            success: function(res){
              $('#custCrudModal').html("Edit Customer");
              $('#ajax-modal').modal('show');
              $('#custId').val(res.custId);
              $('#fname').val(res.fname);
              $('#lname').val(res.lname);
              $('#email').val(res.email);
           }
        });

    });

    $('body').on('click', '.delete', function () {

       if (confirm("Delete Record?") == true) {
        var id = $(this).data('id');
         
        // ajax
        $.ajax({
            type:"POST",
            url: "delete.php",
            data: { id: id },
            dataType: 'json',
            success: function(res){

              $('#fname').html(res.fname);
              $('#lname').html(res.lname);
              $('#email').html(res.email);
              window.location.reload();
           }
        });
       }

    });

    $('#custForm').submit(function() {
         
        // ajax
        $.ajax({
            type:"POST",
            url: "add-update.php",
            data: $(this).serialize(), // get all form field value in 
            dataType: 'json',
            success: function(res){
             window.location.reload();
           }
        });

    });

});
</script>
</body>
</html>

Step 4 – Create add-update.php

In step 4, create new file that named add-update.php file. It’s used to add and update form form data into mysql database using ajax.

So, add the below code into your add-update.php file:

<?php

if(count($_POST)>0)
{    
     include 'mydbCon.php';
     
     $fname = $_POST['fname'];
     $lname = $_POST['lname'];
     $email = $_POST['email'];

     if(empty($_POST['custId'])){
 
      $query = "INSERT INTO customers (fname,lname,email)
      VALUES ('$fname','$lname','$email')"; // insert data into database

     }else{
       $query = "UPDATE customers set custId='" . $_POST['custId'] . "', fname='" . $_POST['fname'] . "', lname='" . $_POST['lname'] . "', email='" . $_POST['email'] . "' WHERE custId='" . $_POST['custId'] . "'"; // update form data from the database
     }

    $res = mysqli_query($dbCon, $query);

    if($res) {

     echo json_encode($res);

    } else {

     echo "Error: " . $sql . "" . mysqli_error($dbCon);

    }

}

?>

Step 5 – Create edit.php

In step 5, create new file that named edit.php file. It’s used to fetch data from database using ajax and display in bootstrap form.

So, add the below code into your edit.php file:

<?php
    include "mydbCon.php";
 
    $id = $_POST['id'];

    $query="SELECT * from customers WHERE custId = '" . $id . "'";

    $result = mysqli_query($dbCon,$query);

    $cust = mysqli_fetch_array($result);

    if($cust) {

     echo json_encode($cust);

    } else {

     echo "Error: " . $sql . "" . mysqli_error($dbCon);

    }
 
?>

Step 6 – Create delete.php

In step 6, create new file that named delete.php file. It is used to delete data from mysql database.

So, add the below code into your delete.php file:

<?php


include 'mydbCon.php';

$id = $_POST['id'];

$query = "DELETE FROM customers WHERE custId='" . $id . "'"; // Delete data from the table customers using id

$res = mysqli_query($dbCon, $query);

if($res) {

 echo json_encode($res);

} else {

 echo "Error: " . $sql . "" . mysqli_error($dbCon);

}


?>

The PHP Ajax MySQL Add Edit Delete Same Page will look like in following image:

PHP MySQL Add Edit Delete Same Page using ajax

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

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