简体   繁体   中英

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.

PHP class

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. 20 rows only.

Thanks in advance!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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