您的代码缺少对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/>";
}