Forum Moderators: coopster
I'm attempting to iterate through an array for the purpose of listing its elements in a report. This is a problem that will be replicated several times in my application in various ways.
The array is the result of:
$StudNoteQry = mysql_query("select STUDNOTE_DATE, STUDNOTE from STUDENT_NOTES where STUDENT_NOTES.STUD_ID = '$SelectID'");
$notes = mysql_fetch_array($StudNoteQry, MYSQL_ASSOC);
<?php
if ($notes!= ""){
foreach ($notes as $value){
echo "$value<br>";
}
}
?>
This produces only the first STUDNOTE item and the first STUDNOTE_DATE item. What have I overlooked? I attempted to advance the internal array pointer with $i++ after the echo statement. As I understand it, foreach should advance the pointer automatically.
Grateful for any help,
PianoGuy
This only gets one result.
You should do it like this:
while ($notes = mysql_fetch_array($StudNoteQry, MYSQL_ASSOC)) echo "$notes[STUDNOTE]<br>";
mysql_fetch_array() returns false if there are no records, so the while () loop will kepe going until you run out of rows.
<added>well done DC, beat me to that one</added>
[edited by: vincevincevince at 5:44 pm (utc) on Oct. 11, 2005]
while ($notes = mysql_fetch_assoc($StudNoteQry))
{
echo "Studnote: ". $notes['STUDNOTE'] ." Studnote date: ". $notes['STUDNOTE_DATE'] ."<br>";
}
Or if you really want the foreach loop (eg. you don't know how many fields there are in db) do:
while ($notes = mysql_fetch_assoc($StudNoteQry))
{
foreach ($notes as $key => $value)
{
echo "$key: $value  ";
}
echo "<br>";
}
The problem is that mysql_fetch_array fetches only one mysql result row and then moves the pointer ($StudNoteQry). Hope these all explanations help you understand.
Best regards
Michal Cibor