Skip to content
Advertisement

How can I use mysqli_fetch_array() twice?

I am using the entries from a database to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. I need to loop mysqli result more than once. This doesn’t work:

JavaScript

How can I apply mysqli_fetch_array twice on the same result?

Advertisement

Answer

You don’t need the while loop and you don’t need to use mysqli_fetch_array() at all!

You can simply loop on the mysqli_result object itself many times. It implements Traversable interface that allows it to be used in foreach.

JavaScript

However, you should separate your DB logic from your display logic and to achieve this it is best to use fetch_all(MYSQLI_ASSOC) in your DB logic to retrieve all records into an array.

If you fetch all the data into an array, you can loop that array as many times as you want.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement