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.
Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.
First, connect to a MySQL database. Check it out the connecting to MySQL database using PDO tutorial for detail information. Then, construct a SELECT statement and execute it by using the query() method of the PDO object. The query() method of the PDO object returns a PDOStatement object, or false on failure.
To select data from a table using PDO, you can use: The query() method of a PDO object.
This code below will do what you are asking for:
$sql = $dbh->prepare("SELECT * FROM users ORDER BY id ASC");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
echo $result['username']."<br/>";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With