PHP exit and choice from PDO?

Yesterday I found out that PHP has a yield() method. I did not know about its usefulness in PHP.

A staff member said that this could help SQL statements returning many rows causing potential memory problems. I believe it referenced fetchAll() . But instead of using fetchAll() you can also use fetch() and process the lines one by one. Thus, yield() not the key to solving the problem it refers to.

Am I missing something about yield() vs fetch() here? Are there any more benefits when using yield() and generators?

PS: It is true that it is easier to write clean, readable and maitainable code in large applications with yield() than with fetch() .

+7
yield php mysqli pdo fetch
source share
1 answer

So, yield () is not the key to solving the problem it refers to.

That's right.

But this may allow you to mask the while() / fetch() sequence as a call to foreach() , if you prefer, without the extra memory overhead.

However, PDO is not a good example, because PDOStatement already implements a workaround interface and therefore can be repeated using foreach () :

 $stmt = $pdo->query('SELECT name FROM users'); foreach ($stmt as $row) { var_export($row); } 

So let's take mysqli as an example API, which can only stream results one by one.
Edit Actually, since 5.4.0 mysqli supports Traversable , so it makes no sense to use the exit with mysqli_result. But, let me keep this for a demonstration purpose.

Create such a generator

 function mysqli_gen (mysqli_result $res) { while($row = mysqli_fetch_assoc($res)) { yield $row; } } 

and now you can get strings using foreach with no overhead:

 $res = $mysqli->query("SELECT * FROM users"); foreach (mysqli_gen($res) as $row) { var_export($row); } 
+9
source share

All Articles