Page 1 of 1

WHILE function repeating too many times

Posted: Mon Nov 30, 2009 4:20 pm
by dreeves
I am trying to fill in 3 rows with data retrieved from a table. With my code below, each record is successfully retrieved and displayed, however, each is repeated three times.

Code: Select all

 
$query="SELECT * FROM table where nidid=100";
$result=mysql_query($query, $link);
$num=mysql_numrows($result);
mysql_close($link);
<?php
$i=0;
while ($i < $num) {
$invoiced_activity_id=mysql_result($result,$i,"invoiced_activity_id");
$nidid=mysql_result($result,$i,"nidid");
$om_agreement=mysql_result($result,$i,"om_agreement");
?>
<TR>
    <TD><?php echo $invoiced_activity_id;?></TD>
    <TD><?php echo $nidid;?></TD>
    <TD><?php echo $om_agreement;?></TD>
</TR>
<?php
$i++;
}
?>
 
 
(Incorrect) Output:
ID#3 ...
ID#3 ...
ID#3 ...
ID#4 ...
ID#4 ...
ID#4 ...
ID#5 ...
ID#5 ...
ID#5 ...

I would like it to list each record only once.

Re: WHILE function repeating too many times

Posted: Mon Nov 30, 2009 5:36 pm
by Weiry
Why not use an associative array? The loop for retrieving data is easier than using $i.

Code: Select all

$query = "SELECT * FROM table where nidid=100";
$result = mysql_query($query, $link);
mysql_close($link);
<?php
while ($row = mysql_fetch_assoc($result)) {
    $invoiced_activity_id = $row["invoiced_activity_id"];
    $nidid = $row["nidid"];
    $om_agreement = $row["om_agreement"];
?>
<TR>
    <TD><?php echo $invoiced_activity_id;?></TD>
    <TD><?php echo $nidid;?></TD>
    <TD><?php echo $om_agreement;?></TD>
</TR>
<?php
}
?>

Re: WHILE function repeating too many times

Posted: Mon Nov 30, 2009 5:42 pm
by daedalus__
did you try offsets instead of names?

Re: WHILE function repeating too many times

Posted: Tue Dec 01, 2009 9:58 am
by dreeves
Weiry,
I changed my code to use the mysql_fetch_assoc, but it only returned two of the three records. (the last two)

Daedalus,
What do you mean by "offsets"?