How can PHP be optimized to efficiently handle database queries and display results?
To optimize PHP for handling database queries efficiently, you can use prepared statements to prevent SQL injection attacks and improve performance by reusing query execution plans. Additionally, you can limit the number of columns retrieved from the database and use pagination to display a large number of results without overloading the server.
// Example of using prepared statements to optimize database queries in PHP
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo $row['username'] . "<br>";
}