PDO从数据库中获取数据

时间:2012-11-01 18:48:43

标签: php select pdo while-loop fetch

我最近开始使用PDO,之前我只使用了mysql .. 现在我试图从数据库中获取所有数据。

$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.');
}

但它没有显示任何用户,只是一个空白页面..

3 个答案:

答案 0 :(得分:18)

PDO方法fetchAll()返回一个数组/结果集,您需要将其分配给变量,然后使用/遍历该变量:

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

更新(缺少execute()
此外,您似乎没有调用准备语句之后需要发生的execute()方法,而之前实际获取数据:

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

答案 1 :(得分:4)

以下代码可以满足您的要求:

$sql = $dbh->prepare("SELECT * FROM users ORDER BY id ASC");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
    echo $user['username']."<br/>";
}

答案 2 :(得分:0)

您的代码在execute()之后缺少对prepare()的呼叫。执行准备好的语句后,您可以使用fetchAll()获取记录数组。

$getUsers = $DBH->prepare('SELECT * FROM users ORDER BY id ASC');
$getUsers->execute();
$users = $getUsers->fetchAll();
if ($users) {
    foreach ($users as $user) {
        echo $user['username']."<br/>";
    }
} else {
    trigger_error('No users.');
}

但是,在您的示例中,您没有将任何变量数据传递给查询,并且只执行了一次,这违反了准备语句的目的。如果需要在SQL中使用变量,则应使用准备好的语句,例如:

$getUsers = $DBH->prepare('SELECT * FROM users WHERE id=?');
$getUsers->execute([
    $_GET['user_id']
]);
$user = $getUsers->fetch();     // get single user by unique id

如果没有变量,则只需使用query()方法。

$users = $DBH->query('SELECT * FROM users ORDER BY id ASC')->fetchAll();

如果您不需要一次获取所有记录,则只需使用foreach在语句上循环即可。

$getUsers = $DBH->prepare('SELECT * FROM users WHERE username LIKE ? ORDER BY id ASC');
$getUsers->execute([
    '%' . $_GET['search'] . '%'     // search for username with wildcards
]);
foreach ($getUsers as $user) {
    echo $user['username']."<br/>";
}