What are common pitfalls when retrieving multiple rows from a MySQL table using PHP?

One common pitfall when retrieving multiple rows from a MySQL table using PHP is not properly iterating over the result set. It's important to use a loop, such as a while loop, to fetch each row individually. Failure to do so can result in only the first row being returned or other unexpected behavior.

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

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

// Query to retrieve multiple rows from a table
$query = "SELECT * FROM table_name";
$result = $connection->query($query);

// Check if there are any rows returned
if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

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