Invalid argument error in foreach

Asked

Viewed 52 times

0

<?php


if (isset($_POST['sendRecover'])) {
    $recover = strip_tags(trim($_POST['email']));
    $readRec = read($link, 'up_users', "WHERE email = '$recover'");

    if (!$readRec) {
        $rc = mysqli_fetch_array($readRec) >= 1;
        echo '<span class="ms no">Erro: Email Inválido!</span>';
    } else {
        foreach ($readRec as $rec) {
            if ($rec['nivel'] == 1 || $rec['nivel'] == 2) {
              }
?>

I don’t know why I made a mistake:

Warning: Invalid argument supplied for foreach() in D: wamp64 www CURSOS projeto_pro_php admin lembrar_password.php on line 15

There is a mysqli query before that comes from a function but select is right, already tested, my syntax there is wrong and I did not hit.

  • This Warning general rule means that the foreach is not receiving a array as it should. I suggest that before the foreach do var_dump($readRec); to be sure of exactly what is being passed on.

  • varival is not an array returned a path, so I switched to print_f, then returned me the amount of a record, but worth!!

2 answers

2

Update
First, keep in mind that a warning is not a mistake.
What may have generated this warning is the fact that foreach have in its syntax the format:

foreach (array_expression as $value)

Make sure the function read() return an array to $readRec.

Read more here, in the PHP manual.

  • 1

    While I don’t quite understand the code, I disagree with your assertion that warnings can be ignored. If it generated a warning, it is because there is something that can result in a problem, it may not be now, but in the future. I think we should always stay alert until alerts and try to solve as much as possible.

  • 1

    I edited the answer keeping in mind your remark and other details I noted in the code

  • varival is not an array returned a path, so I switched to print_f, then returned me the amount of a record, but worth!!

0

It is always valid to check the variable that goes to foreach, we always need to maintain the integrity of the data, ensuring that even if you receive nothing, always agree with the structure of the function, in your case, simply check if it is a valid array:

if ( !is_array($readRec) || count($readRec) < 1 ) {
    // Não é um array válido ou não possui conteúdo.
}
  • varival is not an array returned a path, so I switched to print_f, then returned me the amount of a record, but worth!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.