chizijs chizijs - 1 year ago 75
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");
if(count($getUsers) > 0){
while($user = $getUsers->fetch()){
echo $user['username']."<br/>";
error('No users.');

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

Answer Source

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");
$users = $getUsers->fetchAll();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download