I have had problema with "foreach"…
<?php
/*** user ***/
$sql = "SELECT * FROM user WHERE user_login = '$login' ";
$users = selecionar($sql);
foreach($users as $user) {
$userId = $user['user_id'];
}
?>
<?php
$sqll = "SELECT * FROM cadastro WHERE user_id = '$userId' ";
$cadastro = selecionar($sqll);
foreach($cadastro as $cad) { ?> /* Line 41 */
..... HTML
<?php } ?>
If I register something in PhpMyAdmin this code shows the register. But if there’s not register in DB the page shows
Warning: Invalid argument supplied for foreach() in C:wamp64wwwbanheiromovel 2-listagemlistagem_perfil.php on line 41
2
Answers
It looks like
selecionar()
returns something that isn’t iterable if there are no results, like maybenull
orfalse
. (Remember that if your function doesn’t reach areturn
statement it’s going to returnnull
.)I think your two best options are either
Wrap the
foreach
in a conditional to make sure it’s not empty before you try to iterate itModify
selecionar()
so that it always returns an array, but just returns an empty array if the query returns no results.I prefer the second one, personally. You can do this by initializing whatever variable you’re fetching your query results into in the function to an empty array, then returning that variable after you (possibly) fill it with data.
Like this:
Also, you should be executing those queries using prepared statements. Inserting input into the SQL string like that is not safe.
Try the following
I had the same problem and i resolved by adding an array() .