Cameeob2003
Cameeob2003

Reputation: 482

PDO returning execute results to an array

So I am bashing my head against the wall over a question which more than likely has a simple solution. Here is my code.

public function login($username, $password){

        $sql = "SELECT * FROM users WHERE username = :user AND password = :pass";
        $stmt = $this->pdo->prepare($sql);
        $data = array('user' => $username, 'pass' => md5($password . $this->salt));
        $stmt->execute($data);

        $status = $stmt->fetchColumn();
        if($status){
            echo "You are Logged in!";
            print_r($result);
        } else {
            echo $status;
            $this->error['alert'] = "You have not entered the correct login information.";
            Users::ErrorReport();
        }

    }

What I want to do is pull all of the data from that users row and store it in an array so that I can access it in order to store it to the class variables. I would like to do something similar to

while($row = $stmt->fetchAll()){
   $this->username = $row['username'];
}

The problem when I do this is Ive run into a million nasty errors and cant find any solutions while searching the net.

Upvotes: 2

Views: 12807

Answers (1)

Adi
Adi

Reputation: 5179

Use fetch() instead of fetchAll()

while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
   $this->username = $row['username'];
}

or if you like, you can use fetchAll() this way

$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC)

Update: Venu is right, it's a bit wasteful to use mixed (Numeric and Associative) if you're only gonna use associative. So it's a good idea to use PDO::FETCH_ASSOC

Upvotes: 4

Related Questions