0

I have this method that I want to give me all usernames in the database, in a list.

I know that fetch() should be inside a look of some kind. But I don't know how to loop inside an object, because I've tried with a for and a while and I've got this error that says that it cannot be treated as an array or string (ie: Catchable fatal error: Object of class PDOStatement could not be converted to string).

So, How do I do a loop inside a result set?

The code below is my last attempt, and it shows only the first result (naturally, because it should be inside some kind of loop). I've looked into some other questions here, but as I'm just starting with objects, they are too complex and I cannot quite grasp the concept.

function getUsuarios() {
        $usuariosRaw = $this->pdo->query('SELECT nombre FROM usuarios');
        $listadoUsuarios = $usuariosRaw->fetch();   
        echo 'Listado de Reservas:<br>';
        echo $listadoUsuarios['nombre'].'<br>';
    }
2

2 Answers 2

1
function getUsuarios() {
        $usuariosRaw = $this->pdo->query('SELECT nombre FROM usuarios');
        $listadoUsuarios = $usuariosRaw->fetchAll();   
        echo 'Listado de Reservas:<br>';
       foreach( $listadoUsuarios  as $row ) 
{ 
echo $row['nombre'].'<br>';
}
    }

Is not working?

Sign up to request clarification or add additional context in comments.

1 Comment

It works! THANKS!! (there's a $ missing before listadoUsuarios and the system didn't allow me to edit your post with just one character)
0

connection to pdo :

function connect() {
try {
    $dbh = new PDO('mysql:dbname=test;host=localhost','root', 'root');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
    echo $ex->getMessage();
}

return $dbh;

}

function to get users :

function getUser(\PDO $dbh){
 $sql = 'SELECT name FROM users';
 $stmt = $dbh->query($sql);
 $result = $stmt->fetchAll(5); // PDO::FETCH_OBJ
 return $result;
}

loop to get results :

    <?php 
      require_once 'db.php';
      $dbh = connect();
     $users = getUser($dbh);
    ?>


    <?php foreach($users as $user):?>
       <p><?= $user->name; ?></p>
    <?php endforeach; ?>

hope that help you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.