PDO get data from database(PDO 从数据库中获取数据)
问题描述
我最近开始使用 PDO,之前我只使用 MySQL.现在我正在尝试从数据库中获取所有数据.
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.
推荐答案
PDO
方法 fetchAll()
返回一个数组/结果集,您需要将其分配给一个变量,然后使用/迭代该变量:
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 />';
}
更新(缺少execute()
)
此外,您似乎没有调用 execute()
方法需要在之后你准备语句但之前你实际获取数据:
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();
...
这篇关于PDO 从数据库中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PDO 从数据库中获取数据


- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01