How can the use of mysql_query in PHP be optimized for looping through database results?

When looping through database results using mysql_query in PHP, it is important to optimize the process by fetching all the results at once and storing them in an array. This reduces the number of queries sent to the database and improves performance.

// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Query the database
$result = mysqli_query($conn, "SELECT * FROM table");

// Fetch all results and store them in an array
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
}

// Loop through the results
foreach ($rows as $row) {
    // Process each row
}

// Close the connection
mysqli_close($conn);