php签到逻辑实现
PHP签到逻辑实现
数据库设计
创建用户签到表,包含字段如用户ID、签到日期、连续签到天数等。示例SQL:
CREATE TABLE user_check_in (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
check_in_date DATE NOT NULL,
consecutive_days INT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
基础签到功能
检查用户今日是否已签到,未签到则插入记录:
function checkIn($userId) {
$today = date('Y-m-d');
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 检查今日是否已签到
$stmt = $pdo->prepare("SELECT id FROM user_check_in WHERE user_id = ? AND check_in_date = ?");
$stmt->execute([$userId, $today]);
if ($stmt->fetch()) {
return ['status' => false, 'message' => '今日已签到'];
}
// 插入签到记录
$stmt = $pdo->prepare("INSERT INTO user_check_in (user_id, check_in_date) VALUES (?, ?)");
$stmt->execute([$userId, $today]);
return ['status' => true, 'message' => '签到成功'];
}
连续签到计算
通过查询昨日签到记录判断是否连续签到:
function getConsecutiveDays($userId) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
// 获取昨日签到记录
$stmt = $pdo->prepare("SELECT consecutive_days FROM user_check_in WHERE user_id = ? AND check_in_date = ?");
$stmt->execute([$userId, $yesterday]);
$lastRecord = $stmt->fetch();
$consecutiveDays = 1;
if ($lastRecord) {
$consecutiveDays = $lastRecord['consecutive_days'] + 1;
}
// 更新今日连续天数
$stmt = $pdo->prepare("UPDATE user_check_in SET consecutive_days = ? WHERE user_id = ? AND check_in_date = ?");
$stmt->execute([$consecutiveDays, $userId, $today]);
return $consecutiveDays;
}
签到奖励系统
根据连续签到天数发放不同奖励:

function giveCheckInReward($userId, $consecutiveDays) {
$rewards = [
1 => ['points' => 10],
3 => ['points' => 30],
7 => ['points' => 100]
];
if (isset($rewards[$consecutiveDays])) {
$reward = $rewards[$consecutiveDays];
// 发放奖励逻辑
return ['status' => true, 'reward' => $reward];
}
return ['status' => false];
}
完整调用示例
$userId = 123;
$checkInResult = checkIn($userId);
if ($checkInResult['status']) {
$consecutiveDays = getConsecutiveDays($userId);
$rewardResult = giveCheckInReward($userId, $consecutiveDays);
if ($rewardResult['status']) {
echo "签到成功!连续签到{$consecutiveDays}天,获得{$rewardResult['reward']['points']}积分";
} else {
echo "签到成功!连续签到{$consecutiveDays}天";
}
} else {
echo $checkInResult['message'];
}
注意事项
- 使用事务处理确保数据一致性
- 考虑时区问题,使用服务器统一时区处理日期
- 高频访问时考虑添加缓存层
- 定期清理历史签到数据






