What are some best practices for handling MySQL query results in PHP to avoid only retrieving the first row of data?

When retrieving MySQL query results in PHP, it is important to iterate through all the rows of data to avoid only retrieving the first row. One common practice is to use a loop, such as a while loop, to fetch each row of data until there are no more rows left. This ensures that all rows are processed and not just the first one.

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

// Query to retrieve data
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Check if there are any rows returned
if (mysqli_num_rows($result) > 0) {
    // Loop through each row of data
    while ($row = mysqli_fetch_assoc($result)) {
        // Process each row of data
        echo $row['column_name'] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close database connection
mysqli_close($connection);