What are some best practices for querying a database in PHP to improve performance?

To improve performance when querying a database in PHP, it is important to use prepared statements to prevent SQL injection attacks and to reduce the overhead of repeatedly parsing the same query. Additionally, limiting the number of columns returned in the query to only those that are necessary can help improve performance by reducing the amount of data transferred between the database and the application. Finally, consider indexing columns that are frequently used in WHERE clauses to speed up query execution.

// Example of using prepared statements to query a database in PHP
$stmt = $pdo->prepare("SELECT column1, column2 FROM table WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);