What best practices should be followed when looping through MySQL query results in PHP to avoid errors like incorrect data display?

When looping through MySQL query results in PHP, it's important to use the appropriate fetch method based on the type of query (e.g., SELECT, INSERT, UPDATE) to avoid errors like incorrect data display. Additionally, always check for the existence of data before trying to access it to prevent errors. Lastly, sanitize and validate the data retrieved from the database to ensure its integrity and security.

// Example of looping through MySQL query results in PHP with best practices
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        // Access and display data safely
        $username = htmlspecialchars($row['username']);
        $email = filter_var($row['email'], FILTER_VALIDATE_EMAIL);
        
        echo "Username: $username, Email: $email <br>";
    }
} else {
    echo "No results found.";
}