PHP页面的Apply Leave下拉菜单包含Annual Leave,No Pay Leave,Compensation Leave三项子菜单。要求监听该子菜单,并在点击子菜单时,查询数据库并在原网页内用表格输出查询的内容。生成PHP完整代码
时间: 2023-12-28 21:03:55 浏览: 78
MySql数据库查询结果用表格输出PHP代码示例
以下是一个可能的解决方案:
HTML部分:
```
<form method="post" action="">
<label for="leave_type">Leave Type:</label>
<select id="leave_type" name="leave_type">
<option value="annual_leave">Annual Leave</option>
<option value="no_pay_leave">No Pay Leave</option>
<option value="compensation_leave">Compensation Leave</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<div id="leave_table"></div>
```
JavaScript部分:
```
<script>
document.getElementById("leave_type").addEventListener("change", function() {
var leave_type = this.value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("leave_table").innerHTML = this.responseText;
}
};
xhr.open("GET", "leave_table.php?leave_type=" + leave_type, true);
xhr.send();
});
</script>
```
PHP部分(leave_table.php):
```
<?php
// Connect to 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);
}
// Get leave type from query string
$leave_type = $_GET["leave_type"];
// Generate SQL query based on leave type
if ($leave_type == "annual_leave") {
$sql = "SELECT * FROM leaves WHERE type='Annual Leave'";
} else if ($leave_type == "no_pay_leave") {
$sql = "SELECT * FROM leaves WHERE type='No Pay Leave'";
} else if ($leave_type == "compensation_leave") {
$sql = "SELECT * FROM leaves WHERE type='Compensation Leave'";
}
// Execute query and generate table
$result = $conn->query($sql);
$table = "<table><tr><th>Date</th><th>Reason</th></tr>";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$table .= "<tr><td>" . $row["date"] . "</td><td>" . $row["reason"] . "</td></tr>";
}
} else {
$table .= "<tr><td colspan='2'>No leaves found.</td></tr>";
}
$table .= "</table>";
// Output table
echo $table;
// Close database connection
$conn->close();
?>
```
这个解决方案使用 JavaScript 监听下拉菜单的变化,并在变化时发送 AJAX 请求到服务器。服务器根据请求中的 leave_type 参数生成对应的 SQL 查询,然后返回一个包含查询结果的 HTML 表格。JavaScript 收到响应后将表格插入到页面中。
阅读全文