php 实现签到

PHP 实现签到功能
数据库设计
创建一个用于存储签到记录的数据表,通常包含用户ID、签到日期等字段:
CREATE TABLE `user_check_in` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`check_in_date` date NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `user_date` (`user_id`,`check_in_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
签到逻辑实现
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 获取当前用户ID(实际应用中从session获取)
$user_id = 1;
$today = date('Y-m-d');
// 检查是否已签到
$stmt = $db->prepare("SELECT id FROM user_check_in WHERE user_id = ? AND check_in_date = ?");
$stmt->execute([$user_id, $today]);
if ($stmt->fetch()) {
echo "今日已签到";
} else {
// 执行签到
$insert = $db->prepare("INSERT INTO user_check_in (user_id, check_in_date) VALUES (?, ?)");
if ($insert->execute([$user_id, $today])) {
echo "签到成功";
} else {
echo "签到失败";
}
}
?>
连续签到功能
// 检查连续签到天数
function getContinuousDays($db, $user_id) {
$days = 0;
$current_date = date('Y-m-d');
while (true) {
$check_date = date('Y-m-d', strtotime($current_date . " -{$days} days"));
$stmt = $db->prepare("SELECT id FROM user_check_in WHERE user_id = ? AND check_in_date = ?");
$stmt->execute([$user_id, $check_date]);
if ($stmt->fetch()) {
$days++;
} else {
break;
}
}
return $days;
}
奖励机制实现
// 根据连续签到天数发放奖励
$continuous_days = getContinuousDays($db, $user_id);
switch ($continuous_days) {
case 7:
grantReward($user_id, '7天奖励');
break;
case 30:
grantReward($user_id, '30天奖励');
break;
}
function grantReward($user_id, $reward_type) {
// 实现发放奖励逻辑
}
签到日历展示
// 获取当月签到记录
function getMonthlyCheckIns($db, $user_id, $year, $month) {
$start_date = "$year-$month-01";
$end_date = date('Y-m-t', strtotime($start_date));
$stmt = $db->prepare("SELECT check_in_date FROM user_check_in
WHERE user_id = ? AND check_in_date BETWEEN ? AND ?");
$stmt->execute([$user_id, $start_date, $end_date]);
$result = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row['check_in_date'];
}
return $result;
}
安全注意事项
- 确保用户认证机制完善,防止伪造签到
- 对数据库操作进行异常处理
- 考虑时区问题,使用服务器统一时区
- 高并发场景考虑使用事务或锁机制
以上实现可根据实际需求进行调整和扩展,如添加签到积分、补签功能等。







