How can PHP developers optimize their code for better performance when fetching and displaying data from a database?

PHP developers can optimize their code for better performance when fetching and displaying data from a database by using techniques like indexing database columns, minimizing the number of queries, using prepared statements, caching data, and optimizing database queries.

// Example of optimizing code by using prepared statements

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

// Prepare a statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind parameters
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch the results
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Display user data
echo "User ID: " . $user['id'] . "<br>";
echo "User Name: " . $user['name'] . "<br>";
echo "User Email: " . $user['email'] . "<br>";