[英]while loop shows only the last row in database when click at button[to display modal dialog]
我在模式對話框中遇到問題。 當用戶單擊“文件”時,將出現模式對話框,並顯示從數據庫獲取的數據。
<?php echo '<table>'; ?>
<tr>
<th>
Name
</th>
<th>
File
</th>
</tr>
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_array($result)) {
$stu_file=$row['file_upload'];
$ins_file=$row['files_uploads'];
$name = $row['name'];
echo "<tr>";
echo "<td>" .$name. "</td>";
echo "<td><a href='#' data-toggle='modal' data-target='#myModal'>File</a></td>";//code this
echo "</tr>";
}
}else{
echo "No data has been done yet!!";
}
?>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Student File</h4>
</div>
<div class="modal-body">
<?php echo"<pre>".$stu_file."</pre>"?>
</div>
<div class="modal-header">
<h4 class="modal-title">Instructor File</h4>
</div>
<div class="modal-body">
<?php echo"<pre>".$ins_file."</pre>"?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal-->
如上面的代碼所示,當我單擊文件時,將顯示模式對話框,但$ stu_file將僅顯示數據庫的最后一行。 當我在while循環內移動模式對話框時,它僅顯示數據庫的第一行。 請幫助解決此問題。
循環的每次迭代都會覆蓋變量$stu_file
和$ins_file
。 這樣,當您到達循環的結尾並打印模式對話框時,這些變量的值就等於循環中的最后一行。 此外,您只有一個模式對話,因此您的方法在這里不起作用。
取而代之的是,將來自數據庫的數據作為JSON對象打印在<script>
標記中,並使用javascript填充必要信息的方式對話框,可能會更容易。
例如,您可以使用以下方式打印出JSON ...
$data = [];
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
echo "<script> var myData = " . json_encode($data) . "; </script>";
現在,您還可以使用data-id
屬性填充鏈接,以對應數據庫中給定的id或PK ,例如echo "<a href='#' data-toggle='modal' data-target='#myModal' data-id='{$row['id']}'>File</a>"
,這樣您就可以在模態的.on('show.bs.modal')
回調中使用它來加載JSON數組中的適當數據。
有關如何使用模式回調的信息,請參閱引導文檔 。 應該是...
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var dataId = button.data('id') // Extract info from data-* attributes
// Now you can get the data form your JSON object
var info = myData[dataId]; // or however you set it up
var modal = $(this);
modal.find('.modal-title').text('New message to ' + info);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.