WHILE function repeating too many times

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dreeves
Forum Commoner
Posts: 39
Joined: Thu Oct 22, 2009 8:53 am

WHILE function repeating too many times

Post 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.
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: WHILE function repeating too many times

Post 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
}
?>
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Re: WHILE function repeating too many times

Post by daedalus__ »

did you try offsets instead of names?
dreeves
Forum Commoner
Posts: 39
Joined: Thu Oct 22, 2009 8:53 am

Re: WHILE function repeating too many times

Post 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"?
Post Reply