Answer the question
In order to leave comments, you need to log in
While vs foreach with sql query?
$goods = mysqli_query($connection, "SELECT * FROM `goods` $orderBy LIMIT 6");
foreach ($goods as $item) {
...
}
$goods = mysqli_query($connection, "SELECT * FROM `goods` $orderBy LIMIT 6");
while ($item = mysqli_fetch_assoc($goods)) {
...
}
Answer the question
In order to leave comments, you need to log in
Technically, it doesn't matter. You don't have to worry about such questions.
Practically, neither.
You need to get the query result into an array using mysqli_fetch_all(), and pass this array to another function for further processing. Conclusion for example.
The idea is not to drag the database around with you throughout the application. Connected, received the necessary data, transferred the data itself to another module, and not the connection to the database.
Should, for example, the html generation module know something about the database? Should not. He should be interested in the data itself, and not the means of working with them.
And of course, the code for working with the database should not be mixed with the output code to the browser. This is an axiom.
while ($item = mysqli_fetch_assoc($goods)) {
The content of $item in the second variant is clear.
And here:
What will $item contain ?
foreach ($goods as $item) {
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question