PHP页面的Apply Leave下拉菜单包含Annual Leave,No Pay Leave,Compensation Leave三项子菜单。要求点击子菜单时,查询数据库并在原网页内用表格输出查询的内容。生成PHP完整代码
时间: 2023-12-30 18:02:47 浏览: 61
一个完整的表单处理PHP
以下是一个简单的PHP代码示例,实现了上述功能:
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// 处理提交的表单数据
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$leave_type = $_POST["leave_type"];
// 查询数据库
$sql = "SELECT * FROM leaves WHERE type='$leave_type'";
$result = mysqli_query($conn, $sql);
// 输出查询结果
if (mysqli_num_rows($result) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Type</th><th>Start Date</th><th>End Date</th></tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["type"]. "</td><td>" . $row["start_date"]. "</td><td>" . $row["end_date"]. "</td></tr>";
}
echo "</table>";
} else {
echo "No results found.";
}
// 关闭数据库连接
mysqli_close($conn);
}
?>
<!-- HTML表单 -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<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>
<br><br>
<input type="submit" value="Submit">
</form>
```
注意,以上示例代码仅演示了如何连接数据库、查询数据和输出结果,实际应用中需要根据具体情况进行修改和完善。另外,为了安全起见,需要对用户输入进行一定的验证和过滤,以防止 SQL 注入等攻击。
阅读全文