What are the potential pitfalls of using a while loop in PHP to output database records?

One potential pitfall of using a while loop in PHP to output database records is the risk of infinite looping if the loop condition is not properly defined or if the query result set is not fetched correctly. To avoid this issue, it is important to ensure that the loop condition is based on fetching rows from the result set and that the loop is terminated when there are no more rows to fetch.

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Query to select records from the database
$sql = "SELECT * FROM table_name";
$result = $connection->query($sql);

// Output records using a while loop
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

// Close the database connection
$connection->close();