Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a loop in function php

Tags:

php

Is it possible to return a loop? not the result but the loop it self. I want to create a function in php. For example like this.

function myloop($sql){
$query = mysql_query($sql);

return while(mysql_fetch_assoc($query))
}

The reason i want to create this is for me to avoid repeating code. Anyone can help me? Thank you..

like image 818
thenewbie Avatar asked Dec 15 '22 18:12

thenewbie


1 Answers

No, but you can simulate that with an Iterator for stable released PHP as of today. In PHP 5.5 there will be generators that is close, too.

$lazyQuery = new SqlResultItertor($sql);
foreach ($lazyQuery as $assoc) {
    $assoc; # the result, one per row
}

BTW: PDO and MySqli offer this already out of the box (not lazy query, but the result is traversable), for mysql you need to write such an iterator-result object your own.

For some mysql_* functions related code, see this answer. However the general suggestion as of today is to use PDO or mysqli instead, those offer more out of the box. See How to successfully rewrite old mysql-php code with deprecated mysql_* functions?

like image 190
hakre Avatar answered Dec 24 '22 17:12

hakre