Reputation: 25
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
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