Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 is not showing any users, just a blank page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
505 views
Welcome To Ask or Share your Answers For Others

1 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();
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...