In your code there is no call to execute() after prepare() . After executing the prepared statement, you can get an array of records using 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.'); }
However, in your example, you do not pass variable data to the request, but execute it only once, which contradicts the purpose of preparing the statement. You should use prepared statements if you need variables in your SQL, for example:
$getUsers = $DBH->prepare('SELECT * FROM users WHERE id=?'); $getUsers->execute([ $_GET['user_id'] ]); $user = $getUsers->fetch();
If there are no variables, you can simply use the query() method.
$users = $DBH->query('SELECT * FROM users ORDER BY id ASC')->fetchAll();
If you donβt need to retrieve all the records at once, you can simply loop the statement with 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/>"; }
source share