Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO get data from database

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.

like image 277
chizijs Avatar asked Nov 01 '12 18:11

chizijs


People also ask

How fetch data from database in PHP and display PDO?

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.

How does PDO SELECT data?

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.

Which PDO method should be used to send a SELECT query to the database?

To select data from a table using PDO, you can use: The query() method of a PDO object.


1 Answers

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/>";
}
like image 146
Abiola Babatunde Avatar answered Oct 03 '22 20:10

Abiola Babatunde