Php

HTML5 Inline Editing with PHP, MYSQL & jQuery Ajax

This tutorial will assist you in understanding HTML5 inline editing with PHP and MYSQL, As demonstrated in the previous tutorial HTML inline editing.

We learned how to make any HTML control editable inline by using the contenteditable attribute. Only browsers that support HTML5 will be able to use Inline Editable.

There are many jQuery plugins that provide inline editable functionality, but you can do it much more easily with HTML5 and without the overhead of the jQuery library.

You only need to write some ajax and jquery code to update a record in a MySQL database. This will be helpful for altering a particular column only, not the complete form’s data.

Inline Editing with HTML5, PHP and Mysql

We’ll make a table with a list of all the records. We will add the contenteditable attribute to all 'td's in the table where I need inline editing functionality.

I’ll make a table with a list of all the records. We will add the contenteditable attribute to all 'td's “(td >

Whenever the user changes the TD data, I will capture the event 'focusout' with jQuery and get the updated data of td, then call a php function to update the data into mysql using the changed td data.

This example will include the files listed below:

  1. connection.php: This file is used to create a connection with MySQL.
  2. index.php: This file is used to display records in a table and has an inline editing option.
  3. server.php: This file will respond to an ajax request and update data in mysql.

Also checkout other related tutorials,

Let’s make an ‘inline-edit’ POC project in the xampp/htdocs folder. We’ll make an index.html file here.

Step 1: Include the bootstrap CSS file and the jQuery library in the page’s head section.

<script type="text/javascript" src="jquery-1.11.1.min.js"></script>

Step 2: Created a connection file connection.php for database connection with PHP.

Related Post
<?php
/* Database connection start */$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

/* check connection */if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>

Step 3: Get records from MySQL and save them in a variable, then paste the code below into the index.php file.

<?php
//include connection file 
include_once("connection.php");
$sql = "SELECT * FROM `employee`";
$queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
?>

In this case, I’m fetching data from MySQL in order to display it in an HTML table. You must replace table name 'employee' with the name of your table.

Step 3: Make an HTML table and iterate through the records in each row.

<table id="employee_grid" class="table table-condensed table-hover table-striped bootgrid-table" width="60%" cellspacing="0">
 <thead>
     <tr>
          <th>Name</th>
          <th>Salary</th>
          <th>Age</th>
        </tr>
 </thead>
 <tbody id="_editable_table">
    <?php foreach($queryRecords as $res) :?>
   <tr data-row-id="<?php echo $res['id'];?>">
     <td class="editable-col" >"><?php echo $res['employee_name'];?></td>
     <td class="editable-col" >"><!--?php echo $res['employee_salary'];?></td>
     <td class="editable-col" >"><!--?php echo $res['employee_age'];?></td>
   </tr>
  <?php endforeach;?>
 </tbody>
</table>

To display table data, I use step-2 $queryRecords variable and iterate on tr using PHP foreach() function. As you can see, I have hard coded the col-index='*' attribute on each table td for column name identification. I’ve also added a oldVal='*' attribute to store the table’s old valve; if the new and old values are the same, we won’t send a server request.

I’m also adding the data-row-id="" attribute to each table tr to identify the row-id of data.
This 'id' will be the employee table’s primary key. This indicates which column row we are updating.

Step 4: Created AJAX Using a server-side php script, a jquery request is used to update data in MySQL.

<script type="text/javascript">
$(document).ready(function(){
  $('td.editable-col').on('focusout', function() {
    data = {};
    data['val'] = $(this).text();
    data['id'] = $(this).parent('tr').attr('data-row-id');
    data['index'] = $(this).attr('col-index');
      if($(this).attr('oldVal') === data['val'])
    return false;
    
    $.ajax({   
          
          type: "POST",  
          url: "server.php",  
          cache:false,  
          data: data,
          dataType: "json",       
          success: function(response)  
          {   
            //$("#loading").hide();
            if(response.status) {
              $("#msg").removeClass('alert-danger');
              $("#msg").addClass('alert-success').html(response.msg);
            } else {
              $("#msg").removeClass('alert-success');
              $("#msg").addClass('alert-danger').html(response.msg);
            }
          }   
        });
  });
});

</script>

Here As you can see, I am attaching an event 'focusout' to each td of the table and sending a request if the value of the td changes. First, I am getting the changed value of the td and then I am getting the row-id of the data tuple with the column-id. Aggregate all parameters and send them to the server to update the column value.

Step 5: Now, using server.php, update the data in MySQL.

<?php
  //include connection file 
  include_once("connection.php");
  
  //define index of column
  $columns = array(
    0 =>'employee_name', 
    1 => 'employee_salary',
    2 => 'employee_age'
  );
  $error = true;
  $colVal = '';
  $colIndex = $rowId = 0;
  
  $msg = array('status' => !$error, 'msg' => 'Failed! updation in mysql');

  if(isset($_POST)){
    if(isset($_POST['val']) &amp;&amp; !empty($_POST['val']) &amp;&amp; $error) {
      $colVal = $_POST['val'];
      $error = false;
      
    } else {
      $error = true;
    }
    if(isset($_POST['index']) &amp;&amp; $_POST['index'] >= 0 &amp;&amp;  $error) {
      $colIndex = $_POST['index'];
      $error = false;
    } else {
      $error = true;
    }
    if(isset($_POST['id']) &amp;&amp; $_POST['id'] > 0 &amp;&amp; $error) {
      $rowId = $_POST['id'];
      $error = false;
    } else {
      $error = true;
    }
  
    if(!$error) {
        $sql = "UPDATE employee SET ".$columns[$colIndex]." = '".$colVal."' WHERE id='".$rowId."'";
        $status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
        $msg = array('status' => !$error, 'msg' => 'Success! updation in mysql');
    }
  }
  
  // send data as json format
  echo json_encode($msg);
?>

This is a simple PHP code; I haven’t included any SQL injection prevention code, nor have I combined all valid conditions into a complex PHP code.

Conclusion

I’ve shown you how to use PHP, MySQL, and jQuery AJAX to implement HTML5 inline editing.
Using the HTML5 contenteditable attribute, you can easily integrate inline editing into your application.

Download Code and Demo Link

View Comments

  • Can you help me? Only the first column is editable, when I try any other column the change reflect in the first one.

    • The reason was '$sql = "UPDATE employee SET ".$columns[$colIndex]." = '".$colVal."' WHERE id='".$rowId."'";', i am not sending updated colindex which want to update.

  • hy, thanks the script before but in there i have a question :
    how to make other coumn can be editable. and when iam try to edit the other column the reflect is in first column.

    • i verified in demo,its working fine,can u please share plunker so that i can find your issue.

      • No it's not working, the error handling logic is broken. While $colVal gets the value from $_POST['val'] correctly, it changes $error to false. And for that reason $colIndex never get's the value of $_POST['index'] (so it puts the new updated values to the first column whose id is 0), and the $error is changed back to true, which makes the updated row correct again.

  • Hi, I'm running the script on local Ubuntu/Xammp. Per row only the first field updates fine, second and third overwrite the first and don't change. To create mySQL table I used following:

    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
    CREATE TABLE IF NOT EXISTS `employee` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `employee_name` varchar(50) NOT NULL,
    `employee_salary` varchar(50) NOT NULL,
    `employee_age` varchar(50) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    INSERT INTO `employee` (`id`, `employee_name`, `employee_salary`, `employee_age`) VALUES
    (1, 'John', '1000', '22'),
    (2, 'Judy', '1000', '24'),
    (3, 'Claire', '1000', '26'),
    (4, 'Mike', '1200', '28');

    To see all values in index.php I changed line 4 from:

    $sql = "SELECT * FROM `employee` limit 1,10 ";

    to:

    $sql = "SELECT * FROM `employee` limit 0,10 ";

    I have been fiddeling quite a while on this and will keep on, because it's very nice rocket technology. Some help can be helpful. Thx ;-)

  • Hi thank you for this post. it's really helped.
    And I wondering if I can update the (inline-input-data) with a button to each row, if possible?
    Could you please help me where can I define to follow the button click event?

    • i updated zip file on download link, u can download from there,please make sure db connection params are correct.

  • Hi, Thank you so much for the post! It's very helpful.

    I am facing a problem. The data is not loading into the table. I have created an "emplyoee" table in my database with the exact fields and entered the connection details. It would be grate of you could help me out.

    Thanks in advance!

  • make sure dbname, username and password updated in connnection.php file, the table name should be employee and connection file included into server.php file.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories