首页 > 解决方案 > 我的类 User 中的 all() 方法仅获取结果的原因是什么?

问题描述

为此类中的用户创建了一个类有方法名称 all() 此方法支持它从数据库中获取所有数据但仅在我使用 foreach() 时才获取第一个结果

class User
{
    public int $id;
    public string $first_name;
    public string $last_name;
    public string $email;
    public string $password;
    public string $hash;
    public bool $active;
    protected PDO $Connection;
    protected array $resultSet;
    public function __construct(PDO $Connection)
    {
        $this->Connection = $Connection;
    }

    public function all(): array|bool
    {
        if($statement = $this->Connection->query('select * from users'))
        {
            if($result = $statement->fetchAll(PDO::FETCH_CLASS,'User',[$this->Connection]))
            {
                foreach ($result as $users)
                {
                    $this->resultSet['id'] = $users->id;
                    $this->resultSet['first_name'] = $users->first_name;
                    $this->resultSet['last_name'] = $users->last_name;
                    $this->resultSet['email'] = $users->email;
                    $this->resultSet['password'] = $users->password;
                    $this->resultSet['hash'] = $users->hash;
                    $this->resultSet['active'] = $users->active;
                    return $this->resultSet;
                }
            }
        }
        return false;
    }
}

标签: php

解决方案


在行

return $this->resultSet;

您正在结束该方法。将该行移到 foreach 块之外,下一行。另请记住,由于您要替换结果集中的相同索引,因此不添加新记录,它将仅包含最后一条记录。尝试类似的东西

$this->resultSet[] = [
    'id' => $users->id,
    ...
];

这将为每个循环时间推送一个记录。


推荐阅读