简体   繁体   English

通过PHP类变量获取PDO

[英]PDO fetch through PHP class variable

Can you explain me why this isn't working? 您能解释一下为什么这行不通吗? I'm storing PDO fetch into PHP class variable and then I'm trying to loop it using function call. 我将PDO提取存储到PHP类变量中,然后尝试使用函数调用对其进行循环。

PHP class PHP类

private $conn;
private $id;
private $data = array();

public function __construct($conn, $id) {
    $this->id = $id;
    $this->loadData();
}

private function loadData() {
    $sql = $this->conn->prepare("SELECT * FROM table WHERE id = :id");
    $sql->bindValue(':id', $this->id);
    $sql->execute();

    $this->data = $sql->fetch();
}

public function getData() {
    return $this->data();
}

Script itself 脚本本身

$test = new test($pdo, "100101");

while ($row = $test->getData()) {
    echo $row['item'];
}

There will only be loop as long as the memory limit has been reached. 只要达到内存限制,就只会有循环。 Query should return ca. 查询应返回ca。 20 rows only. 仅20行。

Thanks in advance! 提前致谢!

  1. change fetch() to fetchAll() fetch()更改为fetchAll()
  2. change while to foreach ($test->getData() as $row) 更改为foreach ($test->getData() as $row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM