PHP实现好友信息显示功能的完整指南
在社交网络或即时通讯应用中,显示好友信息是一个核心功能,本文将详细介绍如何使用PHP实现好友信息的显示功能,包括数据库设计、后端逻辑处理以及前端数据展示。
数据库设计
我们需要设计合理的数据库结构来存储用户和好友信息,以下是基本的表结构设计:
-- 用户表 CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, avatar VARCHAR(255) DEFAULT 'default.jpg', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- 好友关系表 CREATE TABLE friends ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, friend_id INT NOT NULL, status ENUM('pending', 'accepted', 'blocked') DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (friend_id) REFERENCES users(id), UNIQUE KEY (user_id, friend_id) );
后端PHP实现
数据库连接
首先创建一个数据库连接文件 db.php
:
<?php $host = 'localhost'; $dbname = 'social_network'; $username = 'root'; $password = ''; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("数据库连接失败: " . $e->getMessage()); } ?>
获取好友列表
创建 get_friends.php
文件来获取当前用户的好友列表:
<?php require_once 'db.php'; session_start(); if (!isset($_SESSION['user_id'])) { die("请先登录"); } $user_id = $_SESSION['user_id']; try { // 获取已接受的好友关系 $stmt = $pdo->prepare(" SELECT f.id, f.friend_id, u.username, u.email, u.avatar FROM friends f JOIN users u ON f.friend_id = u.id WHERE f.user_id = :user_id AND f.status = 'accepted' UNION SELECT f.id, f.user_id, u.username, u.email, u.avatar FROM friends f JOIN users u ON f.user_id = u.id WHERE f.friend_id = :user_id AND f.status = 'accepted' "); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $friends = $stmt->fetchAll(PDO::FETCH_ASSOC); header('Content-Type: application/json'); echo json_encode($friends); } catch (PDOException $e) { die("获取好友列表失败: " . $e->getMessage()); } ?>
获取单个好友信息
创建 get_friend_profile.php
文件来获取特定好友的详细信息:
<?php require_once 'db.php'; session_start(); if (!isset($_SESSION['user_id'])) { die("请先登录"); } $friend_id = $_GET['friend_id'] ?? null; if (!$friend_id) { die("缺少好友ID参数"); } try { // 检查是否是好友关系 $stmt = $pdo->prepare(" SELECT COUNT(*) FROM friends WHERE (user_id = :user_id AND friend_id = :friend_id AND status = 'accepted') OR (user_id = :friend_id AND friend_id = :user_id AND status = 'accepted') "); $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT); $stmt->bindParam(':friend_id', $friend_id, PDO::PARAM_INT); $stmt->execute(); $is_friend = $stmt->fetchColumn() > 0; if (!$is_friend) { die("您不是该用户的好友"); } // 获取好友信息 $stmt = $pdo->prepare(" SELECT id, username, email, avatar, created_at FROM users WHERE id = :friend_id "); $stmt->bindParam(':friend_id', $friend_id, PDO::PARAM_INT); $stmt->execute(); $friend = $stmt->fetch(PDO::FETCH_ASSOC); header('Content-Type: application/json'); echo json_encode($friend); } catch (PDOException $e) { die("获取好友信息失败: " . $e->getMessage()); } ?>
前端实现
显示好友列表
创建 friends_list.php
文件:
<?php require_once 'db.php'; session_start(); if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit; } ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8">好友列表</title> <style> .friend-item { display: flex; align-items: center; padding: 10px; border-bottom: 1px solid #eee; } .friend-avatar { width: 50px; height: 50px; border-radius: 50%; margin-right: 15px; object-fit: cover; } .friend-info { flex-grow: 1; } .friend-name { font-weight: bold; margin-bottom: 5px; } </style> </head> <body> <h1>我的好友</h1> <div id="friends-list"></div> <script> document.addEventListener('DOMContentLoaded', function() { fetch('get_friends.php') .then(response => response.json()) .then(data => { const friendsList = document.getElementById('friends-list'); data.forEach(friend => { const friendItem = document.createElement('div'); friendItem.className = 'friend-item'; friendItem.innerHTML = ` <img src="uploads/avatars/${friend.avatar}" alt="${friend.username}" class="friend-avatar"> <div class="friend-info"> <div class="friend-name">${friend.username}</div> <div class="friend-email">${friend.email}</div> </div> <button onclick="viewProfile(${friend.id})">查看详情</button> `; friendsList.appendChild(friendItem); }); }) .catch(error => console.error('获取好友列表失败:', error)); }); function viewProfile(friendId) { window.location.href = `friend_profile.php?friend_id=${friendId}`; } </script> </body> </html>
显示好友详情
创建 friend_profile.php
文件:
<?php require_once 'db.php'; session_start(); if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit; } ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8">好友详情</title> <style> .profile-container { max-width: 600px; margin: 50px auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .profile-header { text-align: center; margin-bottom: 20px; } .profile-avatar { width: 150px; height: 150px; border-radius: 50%; object-fit: cover; margin-bottom: 15px; } .profile-info { line-height: 1.8; } .back-button { display: inline-block; margin-top: 20px; padding: 8px 16px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; } </style> </head> <body> <?php $friend_id = $_GET['friend_id'] ?? null; if (!$friend_id) { die("缺少好友ID参数"); } try { $stmt = $pdo->prepare(" SELECT id, username, email, avatar, created_at FROM users WHERE id = :friend_id "); $stmt->bindParam(':friend_id', $friend_id, PDO::PARAM_INT); $stmt->execute(); $friend = $stmt->fetch(PDO::FETCH_ASSOC); if (!$friend) { die("好友不存在"); } } catch (PDOException $e) { die("获取好友信息失败: " . $e->getMessage()); } ?> <div class="profile-container"> <div class="profile-header"> <img src="uploads/avatars/<?php echo htmlspecialchars($friend['avatar']); ?>" alt="<?php echo htmlspecialchars($friend['username']); ?>" class="profile-avatar"> <h2><?php echo htmlspecialchars($friend['username']); ?></h2> </div> <
还没有评论,来说两句吧...