我在模态对话框中面临一个问题。当用户点击"文件"时,模态对话框将出现,并将显示从数据库中获取的数据。
<?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-->
正如您看到的上面的代码,当我单击at file时,模态对话框显示,但是$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数组。
查看bootstrap文档了解如何使用模态回调。应该是……
$('#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);
})