# PHP Ajax Update in MySQL Data through  Modal

- Link: https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/
- Published: 2021-01-03T12:38:41+05:30
- Author: Ashishkumar Vishwakarma

In this tutorial, we will update and view data query in a modal using PHP Ajax MySQL
table along with JavaScript/ Sweet alert through Bootstrap Modal by using PHP script
with Ajax jQuery without page refresh.

Also Read: – [Insert Data in PHP Ajax MySQL By Using Bootstrap Modal](https://technotaught.com/insert-data-in-php-ajax-mysql-by-using-bootstrap-modal/)

![Update Data Through Bootstrap Modal by using Ajax PHP](https://technotaught.com/
wp-content/uploads/2021/01/Update-Data-Through-Bootstrap-Modal-by-using-Ajax-PHP-
1024x545.png)

## PHP Ajax Update in MySQL Data through Bootstrap Modal

![](https://technotaught.com/wp-content/uploads/2021/01/update-in-php-view.png)

![view in php](https://technotaught.com/wp-content/uploads/2021/01/Insert-in-php-
view.png)

Bootstrap Modal is a pop-up/ dialog-box that appeared on the web page. Bootstrap
Modal is used to display dynamic data from the database to pop-up/ dialog box, we
use Bootstrap Modal for inserting or updating, or fetch database data. By using 
this plugin we can update or fetch data without open a new page, but we can do on-
page without opening the new web page.

This is the latest concept of inserting / updating data through Bootstrap Modal 
by using the Ajax request method. Here we have to use Ajax jQuery, and we have to
get id from the edit button and store the id by using AJAX jQuery and by using jQuery
we fetch details and show them in a bootstrap modal HTML form field, and we can 
update data and by clicking on the update button and by using jQuery code we have
to display that HTML data on the bootstrap modal. This process has done without 
a page refresh event.

Related:- [Login System Using PHP MySQL And JQuery AJAX](https://technotaught.com/login-system-using-php-mysql-and-jquery-ajax/)

### File need

Now, we will create five files here for the login system.

 1. **db.php –** Connection file contains the connection code for database connectivity
 2. **index**.**php –** Contain all HTML, PHP, AJAX code
 3. **update.php –** PHP code of update and view data

### Source Code

#### Creating the DB File

After creating the table, we need to create a PHP script in order to connect to 
the MySQL database server. Let’s create a file named “db.php” and put the following
code inside it

    ```language-sql
    <?php 
    $con = mysqli_connect("localhost","root","","test");
    ?>
    ```

#### index.php

    ```php
    <?php
    include('db.php');
    $query = mysqli_query($con, "SELECT * FROM files ORDER BY ID DESC");
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Insert Data in PhP</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>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    </head>

    <body>
        <div class="container">
            <h3 align="center">Technotaught - <a href="https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/">Update Data Through Bootstrap Modal by using Ajax PHP</a></h3>
            <br />
            <div class="col-md-2">
            </div>
            <div class="col-md-8">
                <div class="table-responsive">
                    <div id="employee_table">
                        <table class="table table-bordered">
                            <tr>
                                <th width="70%">Title</th>
                                <th width="30%">edit</th>
                                <th width="30%">View</th>
                            </tr>
                            <?php while ($row = mysqli_fetch_array($query)) {

                            ?>
                                <tr>
                                    <td><?php echo $row['title']; ?></td>
                                    <td><a type="button" class="btn btn-info btn-xs edit_data" data-toggle="modal" data-keyboard="false" data-backdrop="static" data-target="#update_data" data-id="<?= $row['id']; ?>" data-title="<?= $row['title']; ?>" data-description="<?= $row['description']; ?>" data-uploaded_on="<?= $row['uploaded_on']; ?>">Edit</a></td>
                                    <td><input type="button" name="view" value="view" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
                                </tr>
                            <?php } ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <!-- ############################################################################################### -->
        <!-- View Data Modal-->
        <div id="dataModal" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        <h4 class="modal-title">View Details</h4>
                    </div>
                    <div class="modal-body" id="employee_detail">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- ############################################################################################### -->
        <!-- Update data-->
        <div class="modal fade" id="update_data" role="dialog">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fa fa-edit"></i> Update Details</h5>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="exampleFormControlInput1">Title</label>
                            <input type="text" class="form-control" id="title1" name="title1">
                        </div>
                        <div class="form-group">
                            <label for="exampleFormControlTextarea1"> Description</label>
                            <textarea class="form-control" id="description1" name="description1" rows="3"></textarea>
                        </div>
                        <input type="hidden" name="id_modal" id="id_modal" class="form-control-sm">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="update_detail" class="btn btn-primary" value="Update">Update</button>
                    </div>
                </div>
            </div>
        </div>
    <!-- ############################################################################################### -->
    </body>
    </html>

    <script>
        $(document).ready(function() {
            $(document).on('click', '.view_data', function() {
                var employee_id = $(this).attr("id");
                $.ajax({
                    url: "insert.php",
                    method: "POST",
                    data: {
                        employee_id: employee_id
                    },
                    success: function(data) {
                        $('#employee_detail').html(data);
                        $('#dataModal').modal('show');
                    }
                });
            });
            $(function() {
                $('#update_data').on('show.bs.modal', function(event) {
                    var button = $(event.relatedTarget);
                    var id = button.data('id');
                    var title = button.data('title');
                    var descripton = button.data('description');
                    var modal = $(this);
                    modal.find('#title1').val(title);
                    modal.find('#description1').val(descripton);
                    modal.find('#id_modal').val(id);
                });
            });
            $(document).on('click', '#update_detail', function() {
                var id = $('#id_modal').val();
                var title1 = $('#title1').val();
                var description1 = $('#description1').val();
                $.ajax({
                    url: "update.php",
                    method: "POST",
                    catch: false,
                    data: {
                        update: 1,
                        id: id,
                        title: title1,
                        description:description1
                    },
                    success: function(dataResult) {
                        var dataResult = JSON.parse(dataResult);
                        if (dataResult.statusCode == 1) {
                            $('#update_data').modal().hide();
                            swal("Data Updated!", {
                                icon: "success",
                            }).then((result) => {
                                location.reload();
                            });    
                        }
                    }
                });
            });
        });
    </script>
    ```

 

#### update.php

File contain PHP code that update and view data.

    ```php
    <?php 

    include('db.php');

    // ##################################################################
    // View Data
    if(isset($_POST["employee_id"]))  
     {  
          $output = '';  
          $query = "SELECT * FROM files WHERE id = '".$_POST["employee_id"]."'";  
          $result = mysqli_query($con, $query);  
          $output .= '  
          <div class="table-responsive">  
               <table class="table table-bordered">';  
          while($row = mysqli_fetch_array($result))  
          {  
               $output .= '  
                    <tr>  
                         <td width="30%"><label>Title</label></td>  
                         <td width="70%">'.$row["title"].'</td>  
                    </tr>  
                    <tr>  
                         <td width="30%"><label>Description</label></td>  
                         <td width="70%">'.$row["description"].'</td>  
                    </tr>  
                    <tr>  
                         <td width="30%"><label>Uploaded_on</label></td>  
                         <td width="70%">'.$row["uploaded_on"].'</td>  
                    </tr>  

               ';  
          }  
          $output .= '  
               </table>  
          </div>  
          ';  
          echo $output;  
     }  
    // ##################################################################
    // Update Data
     if (isset($_POST['update'])) {
    	$id = $_POST['id'];
    	$title = $_POST['title'];
    	$description = $_POST['description'];
    	$sql = "UPDATE `files` 
    	SET `title`='$title',
    	`description`='$description',
    	`uploaded_on`=NOW()
        WHERE id=$id";
    	if (mysqli_query($con, $sql)) {
    		echo json_encode(array("statusCode" => 1));
    	} else {
    		echo json_encode(array("statusCode" => 2));
    	}
    	mysqli_close($con);
    }
    ?>
    ```

#### Creating the Database Table

Execute the following SQL query to create the _users _table in your MySQL database.

Database name should be **test**.

    ```language-sql
    -
    --  Database  `test`
     -- Table `files`  
     -- 

    CREATE TABLE `files` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `description` varchar(255) NOT NULL,
      `uploaded_on` datetime NOT NULL,
      PRIMARY KEY (`id`)  
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `files`
    --

    INSERT INTO `files` (`id`, `title`, `description`, `uploaded_on`) VALUES
    (1, 'techy', 'how ar u', '2021-01-03 11:36:43'),
    (2, 'technotaught', 'technotaught ', '2021-01-03 11:36:34'),
    (3, 'title1', 'description', '2021-01-03 11:40:15'),
    (4, 'title', 'description', '2021-01-02 15:53:03'),
    (5, 'no', 'yes', '2021-01-02 15:55:11'),
    (6, 'hii', 'Ashish', '2021-01-02 20:28:08'),
    (7, 'test1', 'how are you guys', '2021-01-03 12:06:29'),
    (8, 'test12', 'complete\n', '2021-01-03 12:06:21');
    ```

 

Related:-

### Share this:

 * [  X ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=twitter)
 * [  Facebook ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=facebook)
 * [More](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/#)

 * [  WhatsApp ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=jetpack-whatsapp)
 * [  LinkedIn ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=linkedin)
 * [  Email ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?subject=%5BShared%20Post%5D%20PHP%20Ajax%20Update%20in%20MySQL%20Data%20through%20%20Modal&body=https%3A%2F%2Ftechnotaught.com%2Fphp-ajax-update-in-mysql-data-through-modal%2F&share=email)
 * [  Reddit ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=reddit)
 * [  Tumblr ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=tumblr)
 * [  Pinterest ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=pinterest)
 * [  Telegram ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/?share=telegram)
 * [  Print ](https://technotaught.com/php-ajax-update-in-mysql-data-through-modal/#print?share=print)
