本文介绍了PDO将执行结果返回到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在一个问题上扑朔迷离,这个问题很可能有一个简单的解决方案.这是我的代码.

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'];
}

执行此操作时遇到的问题是Ive遇到了100万个令人讨厌的错误,并且在搜索网络时找不到任何解决方案.

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

推荐答案

使用fetch()代替fetchAll()

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

或者,如果您愿意,可以通过这种方式使用fetchAll()

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

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

更新:Venu是正确的,如果只想使用关联,则使用混合(数字和关联)有点浪费.因此,使用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

这篇关于PDO将执行结果返回到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:14