Help Foreach stdClass

Asked

Viewed 38 times

0

Good morning :D I need a light!

I need to take all 'ids' of users of a table and pass to another table, but when I give a foreach it returns me only 1 result as stdClass.

Follows the code:

$stmt = $PDO->prepare("SELECT usuario_id FROM usuario WHERE nivel_usuario = 2");
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_OBJ);

        foreach ($result as $items):            
            echo "<pre>";               
            print_r($items);
            echo "</pre>";
            die();
       endforeach;

Upshot:

stdClass Object
  (
     [usuario_id] => 7
  )

2 answers

0

The die() function terminates the current script, usually used for error handling.

Maybe it is better to follow the query:

$stmt = $PDO->prepare("SELECT usuario_id FROM usuario WHERE nivel_usuario = 2") or die();

OR BETTER

$stmt = $PDO->prepare("SELECT usuario_id FROM usuario WHERE nivel_usuario = 2");
    $stmt->execute() or die();
    $result = $stmt->fetchAll(PDO::FETCH_OBJ);

    foreach ($result as $items):            
        echo "<pre>";               
        print_r($items);
        echo "</pre>";
   endforeach;

Check out at PHP documentation

  • I put die(); to close the script....

  • But the focus is that I can’t get the user table id and put it in another table... row by row

0

The die() inside the foreach, put it outside that will work.

Browser other questions tagged

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