php - Iterating over generators with while

811

I'm writing a PDO wrapper for a new project. A very common pattern with SQL is to write a statement such as

while ($row = $connection->fetch($sql)) {
    ...
}

My wrapper function is essentially this:

public function fetch($query, $bindings)
{
    $stmt = $this->getPdo()->prepare($query);

    $stmt->execute($bindings);

    $stmt->setFetchMode($this->getFetchMode());

    foreach ($stmt as $record) {
        yield $record;
    }
}

But I can't use the values if I call this using awhile loop as above. Doing avar_dump says that$row is a Generator object. If I use aforeach, avar_dump shows the database data, as expected. Is it simply not possible to traverse over generators usingwhile, or have I confused myself here somewhere?

930

Answer

Solution:

Is it simply not possible to traverse over generators using while, or have I confused myself here somewhere?

You have confused yourself ;) In your code sample:

while ($row = $connection->fetch($sql)) {

You actually executefetch() for every iteration of the loop. With generators you typically useforeach():

foreach ($connection->fetch($sql) as $row) {

People are also looking for solutions to the problem: javascript - Push Notification Custom Save Browser id in Database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.