Skip to content
PHP Logo

In the provided PHP code snippet, what is the purpose of the while loop after executing the MySQL query?

The purpose of the while loop after executing the MySQL query is to fetch and process each row of the result set returned by the query. This loop iterates over the result set until all rows have been fetched.

php
// Issue: The while loop is used to fetch and process each row of the result set returned by the MySQL query.
// Solution: Use a while loop to iterate over the result set and fetch each row.

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

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

// Execute MySQL query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

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

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