What are some best practices for optimizing PHP code when retrieving and displaying data from a database?
When retrieving and displaying data from a database in PHP, it's important to optimize your code to ensure efficient performance. One best practice is to minimize the number of database queries by fetching only the necessary data. Additionally, consider using prepared statements to prevent SQL injection attacks and improve security. Finally, caching frequently accessed data can help reduce the load on the database and improve overall speed.
// Example of optimizing PHP code when retrieving and displaying data from a database
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Fetch data with a single query
$stmt = $pdo->prepare("SELECT * FROM users WHERE status = :status");
$stmt->execute(['status' => 'active']);
$users = $stmt->fetchAll();
// Display the data
foreach ($users as $user) {
echo $user['name'] . "<br>";
}