Skip to content
PHP Logo

What is the issue with implementing a loop to display data from a database in PHP?

The issue with implementing a loop to display data from a database in PHP is that it requires connecting to the database, executing a query, fetching the results, and then iterating over the results to display them. This process can be complex and prone to errors if not done correctly. To solve this, you can use PHP's PDO (PHP Data Objects) extension to connect to the database, prepare and execute the query, and fetch the results in a loop to display them.

php
<?php
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
$pdo = new PDO($dsn, $username, $password);

// Prepare and execute a query
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();

// Fetch and display the results in a loop
while ($row = $stmt->fetch()) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
?>