11

我最近开始使用 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.');
}

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

4

3 回答 3

22

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

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

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

$getUsers = $DBH->prepare("SELECT * FROM users ORDER BY id ASC");
$getUsers->execute();
$users = $getUsers->fetchAll();
...
于 2012-11-01T18:53:07.897 回答
7

下面的代码将满足您的要求:

$sql = $dbh->prepare("SELECT * FROM users ORDER BY id ASC");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
    echo $result['username']."<br/>";
}
于 2016-07-06T06:09:31.037 回答
4

您的代码缺少对execute()after的调用prepare()。执行准备好的语句后,您可以使用fetchAll().

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

// Then in your presentation logic you can use the following code to display the data:
if ($users) {
    foreach ($users as $user) {
        echo $user['username']."<br/>";
    }
} else {
    // Whatever your requirement is to handle the no user case, do it here.
    echo '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/>";
}
于 2019-07-26T17:11:10.613 回答