在PHP中,实现表格(table)的动态加载通常需要结合前端技术,如JavaScript和AJAX。这里我们将使用jQuery库来实现一个简单的动态加载表格的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Table</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Your table and other HTML content goes here -->
</body>
</html>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<!-- Table data will be loaded dynamically -->
</tbody>
</table>
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 results";
}
// Return the data as JSON
header('Content-Type: application/json');
echo json_encode($data);
$conn->close();
?>
$.ajax()
方法从PHP脚本获取数据,并将其动态添加到表格中:$(document).ready(function() {
// Load data from the PHP script
$.ajax({
url: 'fetch_data.php',
type: 'GET',
dataType: 'json',
success: function(data) {
// Add the data to the table
var tableData = '';
$.each(data, function(key, value) {
tableData += '<tr>';
tableData += '<td>' + value.id + '</td>';
tableData += '<td>' + value.name + '</td>';
tableData += '<td>' + value.email + '</td>';
tableData += '</tr>';
});
$('#dynamic-table tbody').append(tableData);
},
error: function() {
alert('Error loading data.');
}
});
});
</script>
现在,当页面加载时,表格将从fetch_data.php脚本动态加载数据。请注意,这个示例仅用于演示目的,实际项目中可能需要根据具体需求进行调整。