項目背景與目錄結構
本項目取材於《深入 PHP 與 jQuery 開發》一書,實現一個完整的活動日程表系統。採用**公共目錄隔離**架構提升安全性:
project-root/
├── public/ # Web 根目錄 (DocumentRoot)
│ ├── index.php # 入口文件
│ ├── css/, js/, img/ # 靜態資源
│ └── tmp.html # 靜態化模板
├── include/ # 核心代碼 (外部不可訪問)
│ ├── config.php # 數據庫配置
│ ├── DBClass.php # 數據庫操作類
│ └── functions.php # 公共函數
└── sql/ # 數據庫腳本
└── calendar.sql
本地訪問:https://localhost/index.php
數據庫設計
CREATE DATABASE IF NOT EXISTS `php-jquery_example`
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE TABLE `events` (
`event_id` INT(11) NOT NULL AUTO_INCREMENT,
`event_title` VARCHAR(80) COLLATE utf8_unicode_ci DEFAULT NULL,
`event_desc` TEXT COLLATE utf8_unicode_ci,
`event_start` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`event_end` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`event_id`),
KEY `event_start` (`event_start`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `events` VALUES
(1, 'New Year\'s Day', 'Happy New Year!', '2010-01-01 00:00:00', '2010-01-01 23:59:59'),
(2, 'Last Day of January', 'Last day of the month!Yay!', '2010-01-31 00:00:00', '2010-01-31 23:59:59');
核心功能模組
| 模組 | 技術點 | 文件 |
| 日曆渲染 | PHP 日期計算、HTML 表格生成、當前月份高亮 | include/Calendar.php |
| 事件管理 | CRUD 操作、AJAX 異步交互、表單驗證 | include/EventManager.php |
| 前端交互 | jQuery 事件綁定、模態框、日期選擇器、AJAX 請求 | public/js/calendar.js |
| 數據庫層 | PDO/MySQLi 封裝、預處理語句、事務支援 | include/DBClass.php |
關鍵技術實現
1. 日曆網格生成算法
function generateCalendar($year, $month) {
$firstDay = mktime(0, 0, 0, $month, 1, $year);
$daysInMonth = date('t', $firstDay);
$startWeekday = date('w', $firstDay); // 0=周日
$html = '<table class="calendar">';
$html .= '<tr><th>Sun</th><th>Mon</th>...<th>Sat</th></tr><tr>';
// 填充首行空白
for ($i = 0; $i < $startWeekday; $i++) $html .= '<td></td>';
for ($day = 1; $day <= $daysInMonth; $day++) {
if (($startWeekday + $day - 1) % 7 == 0 && $day != 1) {
$html .= '</tr><tr>';
}
$hasEvent = checkEventExists($year, $month, $day);
$class = $hasEvent ? 'has-event' : '';
$html .= "<td class='$class' data-date='$year-$month-$day'>$day</td>";
}
$html .= '</tr></table>';
return $html;
}
2. AJAX 事件增刪改查
// 前端 jQuery
$('#event-form').on('submit', function(e) {
e.preventDefault();
$.post('ajax/event_save.php', $(this).serialize(), function(res) {
if (res.success) {
$('#modal').modal('hide');
refreshCalendar(); // 重新渲染當月
}
}, 'json');
});
// 刪除事件
$('.event-delete').on('click', function() {
if (confirm('確定刪除?')) {
$.post('ajax/event_delete.php', {id: $(this).data('id')}, function(res) {
refreshCalendar();
}, 'json');
}
});
3. 後端事件保存 (event_save.php)
require_once '../../include/DBClass.php';
$db = new DBClass();
$title = $_POST['title'];
$desc = $_POST['desc'];
$start = $_POST['start'];
$end = $_POST['end'];
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id) {
$sql = "UPDATE events SET event_title=?, event_desc=?, event_start=?, event_end=? WHERE event_id=?";
$db->execute($sql, [$title, $desc, $start, $end, $id]);
} else {
$sql = "INSERT INTO events(event_title, event_desc, event_start, event_end) VALUES(?, ?, ?, ?)";
$db->execute($sql, [$title, $desc, $start, $end]);
}
echo json_encode(['success' => true]);
安全與最佳實踐
- 目錄隔離:核心代碼置於 public 目錄外,防止直接訪問敏感文件
- 預處理語句:所有 SQL 使用參數綁定防注入
- 輸出轉義:HTML 輸出使用
htmlspecialchars() 防 XSS
- CSRF 保護:表單包含 Token 驗證
- 權限控制:會話驗證用戶身份,僅允許操作自己創建的事件
擴展功能建議
- 重複事件規則 (每日/每週/每月/自定義 RRULE)
- 事件提醒 (郵件/短信/站內信,結合 Cron 定時任務)
- 日曆視圖切換 (月/週/日/議程視圖,參考 FullCalendar.js)
- 拖拽調整事件時間 (jQuery UI Draggable/Droppable)
- ICS/iCal 格式導入導出
- 多用戶共享日曆、權限邀請
總結
本項目展示了 PHP + jQuery 經典全棧開發模式:後端負責數據邏輯與安全,前端負責交互體驗與渲染。雖然技術棧相對傳統,但架構清晰、關注點分離,是理解現代前後端分離架構演進的優秀基礎案例。
- 上一篇文章: Yii2 多圖上傳組件 FileInput 詳細使用教程:從基礎配置到異步刪除全流程
- 下一篇文章: PHP 登錄系統實戰:基於 Session 的用戶認證與角色導向完整代碼
Copyright ©
程式碼之家 All Rights Reserved