在PHP页面生成一个2015-2030年的日历,要求突出当前日期,并可以通过点击←→按钮更改月份。并通过连接数据库,把数据库中所有人的所有日程安排内容都输出到对应日期下。请生成完整代码
时间: 2024-02-09 11:10:50 浏览: 34
好的,以下是代码实现:
```php
<!DOCTYPE html>
<html>
<head>
<title>日历</title>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: Arial, sans-serif;
font-size: 14px;
}
table {
border-collapse: collapse;
margin: 20px auto;
}
table th {
background-color: #eee;
font-weight: bold;
padding: 5px;
text-align: center;
border: 1px solid #ccc;
}
table td {
padding: 5px;
text-align: center;
border: 1px solid #ccc;
}
.current {
background-color: #ffc;
font-weight: bold;
}
.event {
background-color: #cfc;
}
</style>
</head>
<body>
<?php
// 连接数据库
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_dbname';
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
echo "连接数据库失败:" . mysqli_connect_error();
exit;
}
// 获取当前年月日
$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
$month = isset($_GET['month']) ? $_GET['month'] : date('m');
$day = date('d');
// 获取上一个月和下一个月的年月
$prev_year = $year;
$prev_month = $month - 1;
if ($prev_month == 0) {
$prev_month = 12;
$prev_year--;
}
$next_year = $year;
$next_month = $month + 1;
if ($next_month == 13) {
$next_month = 1;
$next_year++;
}
// 获取当前月份的天数和第一天是星期几
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$first_day = date("w", mktime(0, 0, 0, $month, 1, $year));
// 输出日历表格
echo "<table>";
echo "<tr><th colspan='7'>$year 年 $month 月</th></tr>";
echo "<tr><th>周日</th><th>周一</th><th>周二</th><th>周三</th><th>周四</th><th>周五</th><th>周六</th></tr>";
$day_count = 1;
echo "<tr>";
// 输出第一天前的空白格子
for ($i = 0; $i < $first_day; $i++) {
echo "<td></td>";
}
// 输出日期格子
while ($day_count <= $days_in_month) {
for ($i = $first_day; $i < 7; $i++) {
if ($day_count == $day && $month == date('m') && $year == date('Y')) {
echo "<td class='current'>$day_count</td>";
} else {
echo "<td>$day_count</td>";
}
// 查询数据库中是否有事件
$sql = "SELECT * FROM events WHERE date = '$year-$month-$day_count'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<br><span class='event'>" . $row['event'] . "</span>";
}
}
$day_count++;
if ($day_count > $days_in_month) {
break;
}
}
echo "</tr><tr>";
$first_day = 0;
}
// 输出最后一行空白格子
for ($i = 0; $i < 7 - $first_day; $i++) {
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
// 输出前一个月和下一个月的链接
echo "<a href='?year=$prev_year&month=$prev_month'>← 上个月</a> | ";
echo "<a href='?year=$next_year&month=$next_month'>下个月 →</a>";
// 关闭数据库连接
mysqli_close($conn);
?>
</body>
</html>
```
这个代码实现了一个简单的日历,支持通过点击左右箭头切换月份,同时也可以从数据库中读取每个日期的事件信息并显示在日历上。注意替换代码中的数据库连接信息。