3

Is there any method to use foreach instead of while with mysqli_fetch_object($query)?

For example:

while($row = mysqli_fetch_object($query)) {
    echo $row->title;
}

How to use it with Foreach?

1 Answer 1

5

IF you have PHP 5.4 you could do this:

// Using iterators (support was added with PHP 5.4)
foreach ( $c->query('SELECT user,host FROM mysql.user') as $row ) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

LIke this you use the iterator to loop through every result set and then you can use it as $row a

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I'm creating an application and I want to make it working with lower php versions, too.
@MMPP Why? You should keep your versions up-to-date
I have all versions up-to-date. I want to allow users to download and use it. That's why I want to make it working with some php versions. However, best answer! Thanks a lot!
Hm. I think there's no other way to actually use a foreach to loop through a result set
No problem. I will keep while.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.