How can PHP code be optimized to improve performance when fetching data from a database?

To optimize PHP code for fetching data from a database, you can use techniques like minimizing the number of queries, selecting only the necessary columns, using prepared statements to prevent SQL injection, and caching results when possible.

// Example of optimized PHP code for fetching data from a database using PDO

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

// Prepare a query with only necessary columns
$stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE id = :id");

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

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

// Close the connection
$pdo = null;

// Process the fetched data
echo $user['name'];