What are the potential pitfalls of using while loops to display database results in PHP?

Using while loops to display database results in PHP can potentially lead to infinite loops if not properly handled. To avoid this issue, it is important to include a condition that checks if there are still rows to fetch from the database before continuing the loop. This can be done by using the mysqli_fetch_assoc() function, which returns an associative array of the current row being fetched, and checking if it returns false when there are no more rows.

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Query to fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Check if there are rows to fetch
if ($result->num_rows > 0) {
    // Output data of each row
    while ($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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