PHP PDO Database



我正在尝试编辑通过javascript中的模态框显示的整个信息,但我只能编辑列表中的第一项,而不能编辑其他项。请告诉我如何编辑/更新下一项。下面是我的代码

<?php 
session_start();
$sessionArr = $_SESSION['user_session'];
include_once '../connection.php';
$userDetails = [];
try{
$userId = $sessionArr['userId'];
// Set the PDO error mode to exception 
$sql = "SELECT * FROM details WHERE iUserId=:USERID ORDER BY id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':USERID'=>$userId));
$userDetails =$stmt->fetchAll(PDO::FETCH_ASSOC);
if($stmt->rowCount() < 0)
{
echo "no data found";
exit;
}
} catch(PDOException $error){
die("ERROR: Could not connect. " . $error->getMessage());
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body> 
<table>
<tr>
<th>Date</th>
<th>Name</th>
<th>Amount</th>
<th>Phone</th>
<th></th>
<th>Action</th>
</tr>
<?php foreach($userDetails as $item): ?>
<tr>
<td><?php print $item['date']; ?></td>
<td><?php print $item['p_name']; ?></td>
<td><?php print $item['amount']; ?></td>
<td><?php print $item['date']; ?></td>
<td></td>
<td><button id="myBtn">Edit</button></td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
</table>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<form action="" method="post">
<p id="emp">
<input type="text" name="e_name" id="e_name" placeholder="<?php echo 
$item['e_name']; ?>" required style='text-transform:uppercase'>
</p>
<input type="submit" Value="Submit" name="submit" id="submit">
</form>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal   
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
首先,

我们需要一个key/id,以便我们可以更新或删除给定的记录。

为此,我们将使用存储在表行中的id,在 data-id 属性中,您可以通过 JS 中的.dataset.id访问它。(请参阅下面的代码中的注释,我解释了(。

如果你想添加一个事件侦听器,你永远不应该做这样的事情:(你的代码(

<td><button id="myBtn">Edit</button></td>

id attribute应始终是唯一的,请改用.class

我知道您想更新值,因此我们将value附加到或name e_name元素,而不是像您那样placeholder

这是工作示例。请阅读我的所有评论,以便您更好地了解正在发生的事情。

// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var editButtons = document.querySelectorAll('.myBtn');
// Get the <span> element that closes the modal
var closeButton = document.querySelector('.close');
// When the user clicks the button, open the modal
// Each edit button we add event 'click' listener 
for (var i = 0; i < editButtons.length; i++) {
    var editButton = editButtons[i];
    editButton.addEventListener('click', function(event) {
    
      // Here we access our row tr, we have data-id with our id in it
      var row = this.closest("tr");
      // Here is your extracted data
      
      // Do whatever you need to
      var rowId = row.dataset.id;
      var rowDate = row.cells[0].innerText;
      var rowName = row.cells[1].innerText;
      var rowAmount = row.cells[2].innerText;
      var rowPhone = row.cells[3].innerText;
      
      // It's our data-action, we can simply switch from one action to another
      if (this.dataset.action === 'edit') {
        // edit stuff... 
        
        // We call to open a modal, simply by using css toggle
        modal.classList.add('visible');
        // We append all data from table row to our form  
        document.getElementById('e_name').value = rowName; 
        document.getElementById('e_amount').value = rowAmount;
        // ... even more stuff
        
      }
      
      if (this.dataset.action === 'delete') {
        // delete stuff
        
        // We want to remove record from db with given `rowId`
        // xhr/ajax request sends `rowId` to your backend 
        
        // you can a function here like removeElement(rowId);
      }
    });
}
closeButton.addEventListener('click', closeModal);
// We call this function whenever we want, 
// eg. We click close button or after successful edit
function closeModal() {
  modal.classList.remove('visible');
}
function onFormSubmit() {
  //do your stuff
  console.log(this);
  
  // do xhr/ajax request
  
  // We prevent the form from reloading the page
  return false;
}
#myModal {
  border: 2px solid black;
  border-radius: 4px;
  padding: 20px;
  display: none;
}
#myModal.visible {
  display: block;
}
#myModal .close {
  cursor: pointer;
  border: 1px solid;
}
<table>
<tr>
<th>Date</th>
<th>Name</th>
<th>Amount</th>
<th>Phone</th>
<th></th>
<th>Action 1</th>
<th>Action 2</th>
</tr>
<tr data-id="1">
<td>12-03-1990</td>
<td>Mark</td>
<td>50</td>
<td>1321132123</td>
<td></td>
<td><button data-action="edit" class="myBtn">Edit</button></td>
<td><button data-action="delete" class="myBtn">Delete</button></td>
</tr>
<tr data-id="1">
<td>01-12-1974</td>
<td>Tom</td>
<td>10</td>
<td>67567576</td>
<td></td>
<td><button data-action="edit" class="myBtn">Edit</button></td>
<td><button data-action="delete" class="myBtn">Delete</button></td>
</tr>
<tr data-id="3">
<td>15-06-1994</td>
<td>Jane</td>
<td>20</td>
<td>987897987</td>
<td></td>
<td><button data-action="edit" class="myBtn">Edit</button></td>
<td><button data-action="delete" class="myBtn">Delete</button></td>
</tr>
</table>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">CLOSE ME</span>
<form action="" method="post" onSubmit="return onFormSubmit();">
<p id="emp">
<input type="text" name="e_name" id="e_name" placeholder="name" value="" required style='text-transform:uppercase'>
<input type="text" name="e_amount" id="e_amount" placeholder="amount" value="" required style='text-transform:uppercase'>
</p>
<input type="submit" Value="Submit" name="submit" id="submit">
</form>
</div>
</div>

最新更新