How can the code be optimized to avoid reading unnecessary data from the database and improve performance?
To optimize the code and improve performance, you can modify the SQL query to only retrieve the necessary data from the database instead of fetching all columns. By specifying the specific columns needed in the SELECT statement, unnecessary data can be avoided, resulting in faster query execution.
// Original code fetching all columns
$query = "SELECT * FROM users WHERE id = :id";
// Optimized code fetching only necessary columns (e.g., name and email)
$query = "SELECT name, email FROM users WHERE id = :id";