What are the advantages and disadvantages of using while loops versus functions for reading and displaying data from a MySQL database in PHP?

When reading and displaying data from a MySQL database in PHP, using functions can help organize and reuse code, making it more modular and easier to maintain. On the other hand, while loops are useful for iterating through result sets and displaying data dynamically. It is often beneficial to combine both approaches, using functions to fetch data from the database and while loops to iterate through the results and display them.

// Using functions and while loops to read and display data from a MySQL database in PHP

// Function to fetch data from the database
function fetchData($conn) {
    $sql = "SELECT * FROM table_name";
    $result = $conn->query($sql);
    return $result;
}

// Establish database connection
$conn = new mysqli("localhost", "username", "password", "database");

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

// Fetch data using the function
$data = fetchData($conn);

// Display data using a while loop
if ($data->num_rows > 0) {
    while($row = $data->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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