How can one efficiently retrieve and display multiple entries from a database using PDO in PHP?
To efficiently retrieve and display multiple entries from a database using PDO in PHP, you can use a prepared statement to fetch the data in a loop and then display it accordingly. This approach minimizes the number of database queries and optimizes the retrieval process.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Prepare a SQL query to retrieve multiple entries
$stmt = $pdo->prepare("SELECT * FROM table_name");
// Execute the query
$stmt->execute();
// Fetch and display the entries
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . "<br>";
}