在PHP中,實(shí)現(xiàn)表格(table)的動(dòng)態(tài)加載通常需要結(jié)合前端技術(shù),如JavaScript和AJAX。這里我們將使用jQuery庫(kù)來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的動(dòng)態(tài)加載表格的示例。
<!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腳本獲取數(shù)據(jù),并將其動(dòng)態(tài)添加到表格中:$(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>
現(xiàn)在,當(dāng)頁(yè)面加載時(shí),表格將從fetch_data.php腳本動(dòng)態(tài)加載數(shù)據(jù)。請(qǐng)注意,這個(gè)示例僅用于演示目的,實(shí)際項(xiàng)目中可能需要根據(jù)具體需求進(jìn)行調(diào)整。