-1

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:\wamp64\www\banheiromovel\02-listagem\listagem_perfil.php on line 41

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kleyton Renato
  • 1
  • 1
  • 1
  • 2

2 Answers2

0

It looks like selecionar() returns something that isn't iterable if there are no results, like maybe null or false. (Remember that if your function doesn't reach a return statement it's going to return null.)

I think your two best options are either

  1. Wrap the foreach in a conditional to make sure it's not empty before you try to iterate it

    if ($users) {
        foreach($users as $user) {
            $userId = $user['user_id'];
        }
    }   
    
  2. Modify 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:

function selecionar(string $sql): array
{
    $result = [];

    // code that executes a query and fetches results,
    // adding the rows to $result if there are any

    return $result;
}

Also, you should be executing those queries using prepared statements. Inserting input into the SQL string like that is not safe.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
-1

Try the following

      /***  user ***/
      $sql = "SELECT * FROM user WHERE user_login = '$login' ";
      $users = selecionar($sql);

        if ($users) {
            foreach(array($users) as $user) {
                $userId = $user['user_id'];
            }
        } 
    ?>

I had the same problem and i resolved by adding an array() .