What are some best practices for optimizing PHP code when working with database queries?

One best practice for optimizing PHP code when working with database queries is to use prepared statements instead of directly inserting variables into your queries. Prepared statements help prevent SQL injection attacks and can also improve performance by allowing the database to cache query plans. Another tip is to only retrieve the data you need from the database by selecting specific columns instead of using "SELECT *". This can reduce the amount of data transferred between the database and the PHP script, resulting in faster query execution.

// Using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();

// Selecting specific columns
$stmt = $pdo->query("SELECT username, email FROM users");
while ($row = $stmt->fetch()) {
    echo $row['username'] . ' - ' . $row['email'] . '<br>';
}