How can I display the comment of the specific row that I want to edit?

2020-02-12 php jquery html mysql ajax

This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML. When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected. However, once I edit it, it does correct the correct row. I can’t figure out a way to display the comment of the row that I want to edit.

I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.

Here is the test case code:

MySQL table has two rows: comment_id as primary row and comment for text. I named the database: testcaseedit_db, and the table: tbl_comment.

index.php

<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

<div id="display_comment"></div>
<div id="comment_message"></div>

<div id="display_edit"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>

$(document).ready(function() {


let count = 0;

$(document).on('click change', '.edit, .submit', function(e) {

  if ($(this).is('.edit')) {

    var comment_id = $(this).attr("id");
    $('#comment_id').val(comment_id);

    var closestDiv = $('button').closest('div.panel'); 
    $('.div.panel').not(closestDiv.next('.div.panel')).hide();
    closestDiv.next('div.panel').slideToggle(100);

    var commentEdit = $('#display_comment').find('#editable').html(); 

  ++count;

  const htmlString = 
  `<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">

    <div class="input-group-prepend">
      <textarea name="comment" id="comment${count}" class="form-control" rows="30" cols="160"> 
        ${commentEdit} ${comment_id} 
      </textarea>
    </div>

    <div class="input-group-prepend">
     <input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
     <input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
    </div>
  </form>`;


  $('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);



    } else if ($(this).is('.submit')) {

    $.ajax({
     url:"edit.php",
     method:"POST",
     data: new FormData(this),
     contentType: false,
     processData: false,
     success:function(data)
     {
      if(data.error != '') {
       $('#comment_form')[0].reset();
       $('#comment_id').val(comment_id);
       $('#comment').val(comment);
      }
     }
    });

   location.reload();

      $(this).closest('form').submit();
      e.stopPropagation();
    } else {
      return false;
    }

});

 // Fetch comment
 function load_comment(){
        $.ajax({
         url:"fetch.php",
         method:"POST",
         success:function(data){
          $('#display_comment').html(data);
         }
        })
 };

 load_comment();


// End of (document).ready(function){}
}); 
</script>


 </body>
</html>

fetch.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
  <div class="panel-body"><b> Comment: </b> <br> <span id="editable">  '.$row["comment"].'  </span> </div>
  <div class="panel-footer" align="right">

  <button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>

  </div>
 </div>
 ';
}


echo $output;

?>

edit.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];

if ( $error == '' && !empty($_POST["comment"]) ) {


 $query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";

 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':comment_id' => $comment_id,
   ':comment'    => $comment
  )
 );

  header("Location: index.php");

} 

$data = array(
 'error'  => $error
);

echo $error;

?>


Answers

Here is the solution:

In fetch.php file, I made the id for each variable into an array as follows:

<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>

And in index.php file, I grabbed the value of each variable as follows:

    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);

Then I displayed the comment variable inside the textarea as follows:

<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>

Here is the full code for index.php and fetch.php. I left edit.php untouched:

index.php

<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

<div id="display_comment"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>

$(document).ready(function() {

let count = 0;

$(document).on('click change', '.edit, .submit', function(e) {

  if ($(this).is('.edit')) {

    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);


    var closestDiv = $('button').closest('div.panel'); 
    $('div.panel').not(closestDiv.next('div.panel')).hide();
    closestDiv.next('div.panel').slideToggle(100);

  ++count;

  const htmlString = 
  `<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">

    <div class="input-group-prepend">
      <textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120"> 
        ${comment}
      </textarea>
    </div>

    <div class="input-group-prepend">
     <input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
     <input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
    </div>
  </form>`;

  $('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);

    } else if ($(this).is('.submit')) {

    $.ajax({
     url:"edit.php",
     method:"POST",
     data: new FormData(this),
     contentType: false,
     processData: false,
     success:function(data)
     {
      if(data.error != '') {
       $('#comment_form')[0].reset();
       $('#comment_id').val(comment_id);
       $('#comment').val(comment);
      }
     }
    });

   location.reload();

      $(this).closest('form').submit();
      e.stopPropagation();
    } else {
      return false;
    }

});

 // Fetch comment
 function load_comment(){
        $.ajax({
         url:"fetch.php",
         method:"POST",
         success:function(data){
          $('#display_comment').html(data);
         }
        })
 };

 load_comment();


// End of (document).ready(function){}
}); 
</script>


 </body>
</html>

fetch.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
  <div class="panel-body"><b> Comment: </b> <br>  '.$row["comment"].' </div>
  <div class="panel-footer" align="right">

  <button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'"  id[2]="'.$row["comment"].'">Edit</button>

  </div>
 </div>
 ';
}

echo $output;

?>

Related