php - 我的类 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;
}
}
解决方案
在行
return $this->resultSet;
您正在结束该方法。将该行移到 foreach 块之外,下一行。另请记住,由于您要替换结果集中的相同索引,因此不添加新记录,它将仅包含最后一条记录。尝试类似的东西
$this->resultSet[] = [
'id' => $users->id,
...
];
这将为每个循环时间推送一个记录。
推荐阅读
- python-3.x - BeautifulSoup 在读取或解析时将内容置于真实元素之外
- wpf - 如何使用滑入式动画为 ItemsControl 中插入的对象设置动画?
- java - 放心获取响应大小(以 KB 为单位)
- android - 测试版到生产
- r - 砖(file.choose())中的错误:找不到函数“砖”
- authentication - formsauthenticationticket 用以前的登录数据解密
- ruby-on-rails - Rails 在 ubuntu 中安装成功,但是当我检查版本时它显示错误
- angular - 角度找不到styles.sass
- laravel - 我使用 pm2 与 (*) 共享的 ViewComposer 执行队列作业而无需暂停
- c++ - 对向量使用 Push Back 功能时的分段错误