What is the correct way to handle database queries and results in PHP to avoid only retrieving the first row of data?

When handling database queries in PHP, it is important to use the appropriate method to fetch results in order to avoid only retrieving the first row of data. To retrieve multiple rows of data, you should use a loop to iterate through the result set and fetch each row individually.

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

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

// Perform a query
$query = "SELECT * FROM table";
$result = $connection->query($query);

// Check if the query was successful
if ($result) {
    // Fetch and display each row of data
    while ($row = $result->fetch_assoc()) {
        echo "Column1: " . $row['column1'] . " - Column2: " . $row['column2'] . "<br>";
    }
} else {
    echo "Error: " . $connection->error;
}

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