I
I
Ibishka2020-04-28 04:56:24
PHP
Ibishka, 2020-04-28 04:56:24

While vs foreach with sql query?

$goods = mysqli_query($connection, "SELECT * FROM `goods` $orderBy LIMIT 6");
foreach ($goods as $item) {
...
}

versus
$goods = mysqli_query($connection, "SELECT * FROM `goods` $orderBy LIMIT 6");
while ($item = mysqli_fetch_assoc($goods)) {
...
}

Which option is better? Many sites use while when showing an example. What do you prefer?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2020-04-28
@Ibishka

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.

M
mahmudchon, 2020-04-28
@mahmudchon

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 question

Ask a Question

731 491 924 answers to any question