What are the best practices for implementing a friendlist feature on a website using PHP and MySQL?
Issue: Implementing a friendlist feature on a website using PHP and MySQL requires creating a database table to store friend relationships, querying the database to retrieve and display the friendlist, and allowing users to add or remove friends. PHP Code Snippet:
// Create a friends table in the database with columns for user_id and friend_id
CREATE TABLE friends (
user_id INT NOT NULL,
friend_id INT NOT NULL,
PRIMARY KEY (user_id, friend_id)
);
// Query the database to retrieve a user's friendlist
$user_id = 1; // Assuming the user's ID is 1
$query = "SELECT friend_id FROM friends WHERE user_id = $user_id";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$friend_id = $row['friend_id'];
// Display the friend's information or perform other actions
}
}
// Allow users to add a friend
$friend_id = 2; // Assuming the friend's ID is 2
$query = "INSERT INTO friends (user_id, friend_id) VALUES ($user_id, $friend_id)";
mysqli_query($conn, $query);
// Allow users to remove a friend
$friend_id = 2; // Assuming the friend's ID is 2
$query = "DELETE FROM friends WHERE user_id = $user_id AND friend_id = $friend_id";
mysqli_query($conn, $query);