PHP实现用户个人主页好友数量统计及指定格式展示
Friends(X) on User Profile Hey there, let's walk through how to implement this friend count feature using your existing database structure. I'll use PDO for database interactions since it's secure and widely recommended, but I'll also include a mysqli alternative if that's what you're working with.
Step 1: Secure Database Connection
First, we need to establish a safe connection to your database. Here's a PDO example:
// Update these with your actual database credentials $host = 'localhost'; $db_name = 'your_database_name'; $db_user = 'your_db_username'; $db_pass = 'your_db_password'; try { $pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("Database connection failed: " . $e->getMessage()); }
Step 2: Retrieve Current User ID
Assuming your users are logged in and their ID is stored in a session (standard practice for user profiles), we'll grab that ID:
session_start(); // Redirect to login if the user isn't authenticated if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; } $current_user_id = $_SESSION['user_id'];
Step 3: Query Friend Count Safely
We'll use a prepared statement to count how many entries exist in the myfriends table where myid matches the current user's ID. This prevents SQL injection risks:
// Prepare and execute the count query $stmt = $pdo->prepare("SELECT COUNT(*) AS friend_count FROM myfriends WHERE myid = :user_id"); $stmt->bindParam(':user_id', $current_user_id, PDO::PARAM_INT); $stmt->execute(); // Fetch the result $friend_data = $stmt->fetch(PDO::FETCH_ASSOC); $friend_count = $friend_data['friend_count'];
Step 4: Output the Formatted Count
Finally, display the count in the exact format you need:
echo "Friends($friend_count)";
Alternative: Mysqli Implementation
If you prefer using mysqli instead of PDO, here's the equivalent code for the query and display steps:
// Connect with mysqli $conn = mysqli_connect($host, $db_user, $db_pass, $db_name); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Prepare and execute query $stmt = mysqli_prepare($conn, "SELECT COUNT(*) AS friend_count FROM myfriends WHERE myid = ?"); mysqli_stmt_bind_param($stmt, "i", $current_user_id); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $friend_data = mysqli_fetch_assoc($result); $friend_count = $friend_data['friend_count']; // Output the formatted count echo "Friends($friend_count)";
Quick Notes
- If a user has no friends,
COUNT(*)will return 0, so it'll displayFriends(0)—which is exactly the expected behavior. - Always use prepared statements when dealing with user-related data (even session-stored IDs) to avoid security vulnerabilities.
- Double-check that your login system correctly stores the user's ID in the session upon authentication.
内容的提问来源于stack exchange,提问作者Alex

