0

I have be struggling to turn the below while loop into a foreach loop with no result, so I am asking for help here on how to do this.

$query = "Select * from TIME_TABLE Where
Extract(month from DATE_FIELD ) = DATE_FORMAT(NOW(), '%c')
and
Extract(day from DATE_FIELD ) = DATE_FORMAT(NOW(), '%e')
order by DATE_FIELD, DESCRIPTION";
$result = $mysqli->query($query);

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $dbItems .=  "<item> <record_num>" . $row['RECORD_NUM'] . "</record_num>" .
        "<date_field>" .   $row['DATE_FIELD'] . "</date_field>" .
        "<description>" .  $row['DESCRIPTION'] . "</description> </item>";
}

PS
I posted this in the wrong group earlier today.

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by kekkaishi
0

what you did seems to be right.
why do you want it to be turned into foreach.
foreach works for arrays only.

0

What I did with the while works. I wanted to learn how to use the foreach for onething but I thought that I could work directley with $results and save a line of code. Does that make sense?

0

No, i think it does not, because as i said above, foreach works with the arrays and in the while your while runs, your result array is in the process of getting formed.i am sure, its still not clear to you.its ok, just work around with the below example i gave .It will definitely help you to understand the use of foreach (this simple and nice example i took from manual) -

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)

experiment with foreach more and you will be the master in it:)

1

just thought id also add in a bit.
remember that mysql fetch array returns only one row each time the query runs, first run returns first row of the mysql resource, the second run second row and so on and returns a false if there is no more... so the cleanest way to go about is to use a while loop as u did IF u r fetching from DB. As network18 said, the best way is to practice and 'explore' be it foreach loop or anything else :)

Votes + Comments
Kekkaishi as good energy and insight
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.