chizijs chizijs - 5 months ago 9
PHP Question

PDO get data from database

I started using PDO recently, earlier I was using just mysql..
Now I am trying to get all data from database.

$getUsers = $DBH->prepare("SELECT * FROM users ORDER BY id ASC");
$getUsers->fetchAll();
if(count($getUsers) > 0){
while($user = $getUsers->fetch()){
echo $user['username']."<br/>";
}
}else{
error('No users.');
}


But it not showing any users, just a blank page..

Answer

The PDO method fetchAll() returns an array/result-set, which you need to assign to a variable and then use/iterate through that variable:

$users = $getUsers->fetchAll();
foreach ($users as $user) {
    echo $user['username'] . '<br />';
}

UPDATE (missing execute())
Also, it appears you aren't calling the execute() method which needs to happen after you prepare the statement but before you actually fetch the data:

$getUsers = $DBH->prepare("SELECT * FROM users ORDER BY id ASC");
$getUsers->execute();
$users = $getUsers->fetchAll();
...