Navbar

My Blog List

Sunday, September 20, 2020

PHP CRUD-5: How to update data in php jquery ajax using Bootstrap Modal (POP-UP Dialog-UP)


Hi Guys. Here in this above video, i have taught about how to update the data with POP Up Dialog Box also known as Bootstrap Modal which is updated into database in php, jQuery, Ajax.

 First, We have taken the Starter Template design from getbootstrap.com website for designing purpose, i.e the Table and the POP Up Bootstrap Modal.

After all thing setup and your data is fetch a table and now you click on edit_button to fetch the data into your POP-Up modal, This is the Link to Fetch the data into TextBox : https://fundaofwebit.blogspot.com/2020/09/fetch-data-in-textbox-in-bootstrap.html .

After fetching data into textbox start with your updating code given below.

Step 1: We have created a table named student with fields and colums names:

1. id (PrimaryKey, AI)
2. fname
3. lname
4. class
5. section

Step 2: Create a file named index.php


<?php session_start(); ?>
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>PHP CRUD -  Bootstrap Modal (POP UP)</title>
</head>
<body>
  

<!-- Student Edit Modal -->
<div class="modal fade" id="editStudentModal" tabindex="-1" role="dialog" aria-labelledby="editStudentModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editStudentModalLabel">Student Edit Data</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
        <form action="code.php" method="POST">
            <div class="modal-body">
                <input type="hidden" name="edit_id" id="edit_id">
                <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" name="fname" id="edit_fname" class="form-control" placeholder="Enter First Name">
                </div>
                <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" name="lname" id="edit_lname" class="form-control" placeholder="Enter Last Name">
                </div>
                <div class="form-group">
                    <label for="">Class</label>
                    <input type="text" name="class" id="edit_class" class="form-control" placeholder="Enter Class">
                </div>
                <div class="form-group">
                    <label for="">Section</label>
                    <input type="text" name="section" id="edit_section" class="form-control" placeholder="Enter Section">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" name="update_student" class="btn btn-primary">Update</button>
            </div>
        </form>
    </div>
  </div>
</div>
<!-- Student Edit Modal -->



    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <?php 
                    if(isset($_SESSION['status']) && $_SESSION['status'] !='')
                    {
                        ?>
                        
                        <div class="alert alert-warning alert-dismissible fade show" role="alert">
                            <strong>Hey!</strong> <?php echo $_SESSION['status']; ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <?php
                        unset($_SESSION['status']);
                    }
                    ?>
                    <div class="card-header">
                        <h5>
                            PHP CRUD -  Bootstrap Modal (POP UP)
                        <!-- Button trigger modal -->
                        <button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#studentModal">
                            Add Student
                        </button>
                        </h5>
                    </div>
                    <div class="card-body">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col">#ID</th>
                                    <th scope="col">First Name</th>
                                    <th scope="col">Last Name</th>
                                    <th scope="col">Class</th>
                                    <th scope="col">Section</th>
                                    <th scope="col">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $conn = mysqli_connect("localhost","root","","phpcrud");
                                $query = "SELECT * FROM students";
                                $query_run = mysqli_query($conn, $query);

                                if(mysqli_num_rows($query_run) > 0)
                                {
                                    // while($row = mysqli_fetch_array($query_run))
                                    foreach($query_run as $row)
                                    {
                                        ?>
                                        <tr>
                                            <td class="stud_id"><?php echo $row['id']; ?></td>
                                            <td><?php echo $row['fname']; ?></td>
                                            <td><?php echo $row['lname']; ?></td>
                                            <td><?php echo $row['class']; ?></td>
                                            <td><?php echo $row['section']; ?></td>
                                            <td>
                                                <a href="#" class="badge badge-primary view_btn">VIEW</a>
                                                <a href="#" class="badge badge-info edit_btn">EDIT</a>
                                                <a href="#" class="badge badge-danger">DELETE</a>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                }
                                else
                                {
                                    echo "<h5>No Record Found</h5>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

    <script>
        $(document).ready(function () {
            
            $('.edit_btn').click(function (e) { 
                e.preventDefault();
                
                var stud_id = $(this).closest('tr').find('.stud_id').text();
                // console.log(stud_id);

                $.ajax({
                    type: "POST",
                    url: "code.php",
                    data: {
                        'checking_edit_btn': true,
                        'student_id': stud_id,
                    },
                    success: function (response) {
                        // console.log(response);
                        $.each(response, function (key, value) { 
                            //  console.log(value['fname']);
                            $('#edit_id').val(value['id']);
                            $('#edit_fname').val(value['fname']);
                            $('#edit_lname').val(value['lname']);
                            $('#edit_class').val(value['class']);
                            $('#edit_section').val(value['section']);
                        });
                        
                        $('#editStudentModal').modal('show');
                    }
                });

            });

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

 Step 3: Create a file named code.php

<?php
session_start();
$conn = mysqli_connect("localhost","root","","phpcrud");

// Student Edit Data
if(isset($_POST['checking_edit_btn']))
{
    $s_id = $_POST['student_id'];
    // echo $return = $s_id;
    $result_array = [];

    $query = "SELECT * FROM students WHERE id='$s_id' ";
    $query_run = mysqli_query($conn, $query);

    if(mysqli_num_rows($query_run) > 0)
    {
        foreach($query_run as $row)
        {
            array_push($result_array, $row);
            header('Content-type: application/json');
            echo json_encode($result_array);
        }
    }
    else
    {
        echo $return = "<h5>No Record Found</h5>";
    }

}


if(isset($_POST['update_student']))
{
    $id = $_POST['edit_id'];
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $class = $_POST['class'];
    $section = $_POST['section'];

    $query = "UPDATE students SET fname='$fname', lname='$lname', class='$class', section='$section' WHERE id='$id' ";
    $query_run = mysqli_query($conn, $query);

    if($query_run)
    {
        $_SESSION['status'] = "Successfully Updated";
        header('Location: index.php');
    }
    else
    {
        $_SESSION['status'] = "Something Went Wrong.!";
        header('Location: index.php');
    }
}

?>


Thanks and Regards,

Ved Prakash N

No comments:

Post a Comment