while in infinite loop using $result = $result->fetch(PDO::FETCH_ASSOC);

Asked

Viewed 1,362 times

1

<?php include ('pdo.php');
class crud
{
    public static function select($arg){
        $pdo = new pdoinit();
        $result = $pdo->prepare($arg);
        $result->execute();
        $resultado = $result->fetch(PDO::FETCH_ASSOC);
        return $resultado;
    }
}
$arr = crud::select('select * from grupos');
print_r($arr);
while ($row = $arr){
    echo $row['nome'];
}
  • $row left where? it was not clear the problem.

  • $Row is a var that will take the information to the while loop, var_dump($arr) will resume this = "Array ( [id_group] => 12 [id_usuario] => 7 [name] => Friends ) "

  • pq u need while? by example seems not to need it.

  • I’m using this while to display information on a grid. <? php while ( $gridGroup = crud::select('select * from groups')){ echo "<tr>"; echo '<th Scope="Row">'. $gridGroup['id_group']. '</th>'; echo '<td>'. $gridGroup['name']. '</td>'; echo '<td>'. ' '.'</td>'; } ?>

  • I think better [Edit] the question and put more details about what you want to do and what is the problem or unexpected result.

1 answer

3


There are two errors in your code.

The first mistake is simple you are endlessly copying all the content of $arr for $row, a solution would be to use foreach.

foreach($arr as $row) {
   echo $row['nome'];
}

Let’s go to the second error, note that you are using the fetch on the line $resultado = $result->fetch(PDO::FETCH_ASSOC); which will return only one line at a time, then result will have an associative array with the first line, recommend using the fetchAll so that line would look like this:

    $resultado = $result->fetchAll(PDO::FETCH_ASSOC);
  • Thank you very much, it worked!

  • 2

    The most important thing is that you understand why the errors and how the code works. ;)

Browser other questions tagged

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