Help Foreach stdClass

0

Good morning: D I need a light!

I need to get all the 'ids' of users from a table and move to another table, but when I give a foreach it returns only 1 result like stdClass.

Follow 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;

Result:

stdClass Object
  (
     [usuario_id] => 7
  )
    
asked by anonymous 02.06.2018 / 16:15

2 answers

0

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

Maybe it's 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 the PHP documentation

    
02.06.2018 / 16:24
0

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

    
03.06.2018 / 00:11