recovering array with PDO

Asked

Viewed 27 times

0

I have a problem that I’ve been through before but I can’t remember how I solved it. The goal is to compare two tables of the database and return only the corresponding values between the two, in my case name and id of the user who is on a team. My class Members possesses id_member and id_team and in it I call this function

public function recuperaMembros(){

    $query = "
    SELECT 
        u.nome, u.id
    FROM
     usuarios AS u
    JOIN 
        membros AS m 
    ON 
        u.id = m.id_membro
    ";

    $stmt = $this->db->prepare($query);
    $stmt->bindValue(':id_membro',$this->__get('id_membro'));
    $stmt->execute();

    return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}

who returns me

Array
(
    [0] => Array
        (
            [nome] => kaue33
            [id] => 24
        )

    [1] => Array
        (
            [nome] => kaue44
            [id] => 25
        )

)

But as you can see, an array contains the rest of the arrays, which in this case would be the return of fetchAll, so I can’t use it normally with indexes like

    $membros = $membro->recuperaMembros();
    $this->view->membros = $membros;

and then use it normally as $this->view->members['name']; for example, how to solve this two-dimensional array problem ? I know you have a way to receive as a common array only. Because if I access $this->view->members[0]['name'] I have access to the array I would like to have, but it would be too extensive and impossible to recover an array practically as an array. If you can help.

1 answer

1

From what I understand you only need to bring a single line from the database. If that’s all, you could better limit your Query using WHERE or LIMIT 1. Another issue you can repair is that you are using fetchAll() which in this case returns the entire query of your dataset. if it is to bring a single line try using only fetch().

  • I really need all the records, for example, a team can have up to 6 members for example, but if it has two precise of the two, ie I capture the team id, in my bd I have a team table and another members table, When comparing members with the Usario id of a given team I want to return all members. I know there’s a way, but I can’t remember. For example, how can I return this array of names and id in a single non-two-dimensional array?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.