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.';
}
ただし、この例では、変数データをクエリに渡さず、1回だけ実行するため、プリペアドステートメントの目的が無効になります。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/>";
}