php 实现关注
实现用户关注功能的 PHP 代码示例
数据库设计 创建两张表:用户表(users)和关注关系表(follows)
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL
);
CREATE TABLE follows (
follower_id INT NOT NULL,
following_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (follower_id, following_id),
FOREIGN KEY (follower_id) REFERENCES users(id),
FOREIGN KEY (following_id) REFERENCES users(id)
);
关注操作
function followUser($followerId, $followingId) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("INSERT INTO follows (follower_id, following_id) VALUES (?, ?)");
$stmt->execute([$followerId, $followingId]);
return $stmt->rowCount() > 0;
}
取消关注操作
function unfollowUser($followerId, $followingId) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("DELETE FROM follows WHERE follower_id = ? AND following_id = ?");
$stmt->execute([$followerId, $followingId]);
return $stmt->rowCount() > 0;
}
检查关注状态
function isFollowing($followerId, $followingId) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("SELECT COUNT(*) FROM follows WHERE follower_id = ? AND following_id = ?");
$stmt->execute([$followerId, $followingId]);
return $stmt->fetchColumn() > 0;
}
获取用户关注列表
function getFollowingList($userId) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("
SELECT u.id, u.username
FROM follows f
JOIN users u ON f.following_id = u.id
WHERE f.follower_id = ?
");
$stmt->execute([$userId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
获取用户粉丝列表

function getFollowerList($userId) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("
SELECT u.id, u.username
FROM follows f
JOIN users u ON f.follower_id = u.id
WHERE f.following_id = ?
");
$stmt->execute([$userId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
前端交互实现
关注按钮HTML
<button id="followBtn" data-user-id="<?php echo $targetUserId; ?>">
<?php echo isFollowing($currentUserId, $targetUserId) ? '已关注' : '关注'; ?>
</button>
AJAX处理关注操作
$('#followBtn').click(function() {
const userId = $(this).data('user-id');
$.post('follow_action.php', {
action: $(this).text() === '关注' ? 'follow' : 'unfollow',
target_id: userId
}, function(response) {
if(response.success) {
$('#followBtn').text(response.isFollowing ? '已关注' : '关注');
}
}, 'json');
});
PHP处理AJAX请求
header('Content-Type: application/json');
$action = $_POST['action'];
$targetId = $_POST['target_id'];
$currentUserId = $_SESSION['user_id']; // 假设用户已登录
$response = ['success' => false];
if($action === 'follow') {
$response['success'] = followUser($currentUserId, $targetId);
$response['isFollowing'] = true;
} elseif($action === 'unfollow') {
$response['success'] = unfollowUser($currentUserId, $targetId);
$response['isFollowing'] = false;
}
echo json_encode($response);
安全注意事项
验证用户身份确保只有登录用户能执行关注操作

session_start();
if(!isset($_SESSION['user_id'])) {
die(json_encode(['error' => '未登录']));
}
防止用户关注自己
if($currentUserId == $targetId) {
die(json_encode(['error' => '不能关注自己']));
}
使用预处理语句防止SQL注入 所有数据库操作示例中已使用PDO预处理语句
性能优化建议
为关注关系表添加索引
CREATE INDEX idx_follower ON follows(follower_id);
CREATE INDEX idx_following ON follows(following_id);
考虑使用缓存减少数据库查询
// 使用Redis缓存关注关系
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = "user:{$followerId}:following:{$followingId}";
if($redis->exists($cacheKey)) {
return (bool)$redis->get($cacheKey);
}






