How can database queries be optimized for fetching user-specific data to display on profile pages in PHP?

When fetching user-specific data to display on profile pages in PHP, it is important to optimize database queries to ensure efficient retrieval of the required information. One way to achieve this is by using prepared statements to prevent SQL injection attacks and improve query performance. Additionally, selecting only the necessary fields and using indexes on columns frequently queried can further enhance the speed of fetching user-specific data.

// Assuming $userId contains the ID of the user whose profile is being viewed

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query to fetch user-specific data
$stmt = $pdo->prepare("SELECT username, email, bio FROM users WHERE id = :userId");

// Bind the parameter and execute the query
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->execute();

// Fetch the data and display it on the profile page
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

echo "Username: " . $userData['username'];
echo "Email: " . $userData['email'];
echo "Bio: " . $userData['bio'];