How to push objects in PHP array after DB query?
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);}