How can the use of foreach loops in PHP lead to incomplete data retrieval from a database and what are alternative solutions?

Using foreach loops in PHP to retrieve data from a database can lead to incomplete data retrieval because the loop may not iterate through all the results returned by the query. This can happen if the data retrieval process is interrupted or if there are errors in the loop logic. One alternative solution is to use a while loop to fetch each row of data from the result set until all rows have been processed.

// Using a while loop to fetch all rows from the result set
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        // Process each row of data here
    }
}