What are some best practices for retrieving and displaying user information based on IDs in PHP?

When retrieving and displaying user information based on IDs in PHP, it is important to validate the input to prevent SQL injection attacks. Additionally, it is recommended to use prepared statements to interact with the database securely. Finally, ensure that the retrieved user information is properly escaped before displaying it to prevent XSS attacks.

<?php
// Assume $userId contains the user ID input from the user
$userId = $_GET['user_id'];

// Validate the input to prevent SQL injection
if (!is_numeric($userId)) {
    die("Invalid user ID");
}

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement to retrieve user information
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();

// Fetch the user information
$user = $stmt->fetch();

// Display the user information
echo "User ID: " . $user['id'] . "<br>";
echo "Username: " . htmlspecialchars($user['username']) . "<br>";
echo "Email: " . htmlspecialchars($user['email']) . "<br>";
?>