How can multiple selections be generated from a database using PHP and avoid the "Invalid argument supplied for foreach()" error?
The "Invalid argument supplied for foreach()" error occurs when trying to iterate over a variable that is not an array or an object. To avoid this error when generating multiple selections from a database using PHP, ensure that the query result is fetched as an array before using a foreach loop to iterate over it.
// Fetch data from the database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Check if data is not empty before iterating
if (!empty($data)) {
foreach ($data as $row) {
// Process each row here
}
} else {
echo "No data found";
}