There is a table with 4 columns. Table cells have contenteditable attribute set. All information is displayed from the database.

<?php foreach($options as $option):?> <tr> <td><?=$option['id']?></td> <td><?=$option['title']?></td> <td class="name" contenteditable><?=$option['name']?></td> <td class="type" data-id ="<?=$option['id']?>" contenteditable> <?=$option['type']?></td> </tr> <?php endforeach; ?> 

It is necessary to do so that the edited information in the cells is saved in the database. I managed to implement saving cells only in the last column. I pass the data-id parameter to the script.js file.

  $('.type').focus(function(){ oldVal = $(this).text(); id = $(this).data('id'); }).blur(function(){ newVal = $(this).text(); if(newVal != oldVal){ $.ajax({ url: 'index.php', type: 'POST', data: {new_val: newVal, id: id}, success: function(res){ console.log(res); }, error: function(){ alert('Error!'); } }); } }); 

Using Ajax, these values ​​are sent to the index.php file, from where they are added to the database:

 function update_option(){ global $db; $type = mysqli_real_escape_string($db, $_POST['new_val']); $id = (int)$_POST['id']; $query = "UPDATE options SET type = '$type' WHERE id = $id"; $res = mysqli_query($db, $query); if( mysqli_affected_rows($db) ) return true; else return false; } 

But this is only for single-column fields. And how to do the same for the "name" field only?

    1 answer 1

    Like this:

     <?php foreach($options as $option):?> <tr> <td><?=$option['id']?></td> <td><?=$option['title']?></td> <td class="name" contenteditable data-id ="<?=$option['id']?>"><?=$option['name']?></td> <td class="type" contenteditable data-id ="<?=$option['id']?>"><?=$option['type']?></td> </tr> <?php endforeach; ?> 

    Js:

     $('.type, .name').focus(function() { oldVal = $(this).text(); id = $(this).data('id'); thisClass = $(this).attr('class'); }).blur(function() { newVal = $(this).text(); if(newVal != oldVal) { $.ajax({ url: 'index.php', type: 'POST', data: {new_val: newVal, id: id, thisClass: thisClass}, success: function(res){ console.log(res); }, error: function(){ alert('Error!'); } }); } }); 

    PHP:

     function update_option(){ global $db; $type = mysqli_real_escape_string($db, $_POST['new_val']); $id = (int)$_POST['id']; if($_POST['thisClass'] == 'name') { $query = "UPDATE options SET name = '".$type."' WHERE id = ".$id; } else if($_POST['thisClass'] == 'type') { $query = "UPDATE options SET type = '".$type."' WHERE id = ".$id; } $res = mysqli_query($db, $query); if( mysqli_affected_rows($db) ) return true; else return false; } 
    • Thank you very much!! Everything turned out))) - Shamil Aslanov