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..
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With