Nebojsa Masic
Nebojsa Masic

Reputation: 25

How to push objects in PHP array after DB query?

I would like to make array of objects with same keys and different values,after fetching data from database.Desirible format after json_encode() looks like this:

[
 {'username':'admin' ,'name':'Sean' ,'lastname':'Paul'},
 {'username':'admin2','name':'Nikola','lastname':'Tesla'},
 {'username':'admin3','name':'Nick','lastname':'Nickolas'}
]

My code looks like this:

private function getUsernames(){

    $sql = "SELECT username,name,lastname FROM users";
    $connect = new Database($username="",$password="");
    $connect->connect();
    $result = $connect->db->query($sql);

      $adminObject = new stdClass();

       while($row = $result -> fetch(PDO::FETCH_ASSOC)){

        $adminObject -> username = $row['username'];
        $adminObject -> name = $row['name'];
        $adminObject -> lastname = $row['lastname'];

        $this->usernames = $adminObject;

    }

This code otput just one object,last one in DB.Is there any solution for this,without using Doctrine,Eloquent or any other ORM?

Upvotes: 2

Views: 178

Answers (1)

Steve
Steve

Reputation: 20469

The output you require is an array of objects, this can be achieved with a single pdo method fetchAll, passing in the correct flag PDO::FETCH_OBJ:

private function getUsernames()
{

    $sql = "SELECT username,name,lastname FROM users";
    $connect = new Database($username = "", $password = "");
    $connect->connect();
    $result = $connect->db->query($sql);

    $this->usernames = $result->fetchAll(PDO::FETCH_OBJ));
    //for your desired json: echo json_encode($this->usernames);
}

Upvotes: 3

Related Questions