Page 1 of 1

Strange Problem when using while with mysql_fetch_assoc

Posted: Sun Nov 20, 2011 1:37 pm
by Live24x7
I am witnessing a strange problem.

My code takes 'earea' figure from a user submitted form and checks if it matches with the 'rarea' stored in another table. It then lists down all entries where the area matches.
The problem is that, if say there are 3 matches, it displays only 2 matches (1 less than the actual number of matches). Strangely mysql_num_rows() gives the correct number.

Can some one point, whats happening. Here's the code:

Code: Select all

// connect to db
 $epin=$_POST['earea']; 
 
 // Comparing Data Begins
$match = mysql_query("SELECT * FROM tabler WHERE rarea='$earea' '" ); // matches user submitted earea against rarea in another table
$row = mysql_fetch_assoc($match); // fethces results
$num_rows = mysql_num_rows($match); 
echo "$num_rows Matches\n"; // display the count of number of matches
?> 
<table border="1"><tr><td>Name</td><td>Area</td><td>Email</td></tr>
<?php while ($row = mysql_fetch_assoc($match))
{ ?>
<tr>
<td width=200> <?php echo $row['rname'] ?> </td>
<td width=200> <?php echo $row['rarea']?></td>
<td width=200> <?php echo $row['remail'] ?></td>
</tr> 
<?php }?>
</table>

so, if echoing $num_rows gives 5 matches
the table generated using while ($row = mysql_fetch_assoc($match) displays only 4 results (-1)

What am i doing wrong ?

Re: Strange Problem when using while with mysql_fetch_assoc

Posted: Sun Nov 20, 2011 6:24 pm
by McInfo
Calling mysql_fetch_assoc() advances the result set pointer. Mysql_fetch_assoc() is called once before the while loop, so the loop starts with the second row of the result set.

Re: Strange Problem when using while with mysql_fetch_assoc

Posted: Mon Nov 21, 2011 1:08 am
by Live24x7
thanks Mcinfo.. So what is the correct way to display the entire list without skipping anything ?

Re: Strange Problem when using while with mysql_fetch_assoc

Posted: Mon Nov 21, 2011 4:57 am
by maxx99
Problem is that you use once

Code: Select all

$row = mysql_fetch_assoc($match); 
above of:

Code: Select all

while ($row = mysql_fetch_assoc($match)

Just don't do it :)

Re: Strange Problem when using while with mysql_fetch_assoc

Posted: Mon Nov 21, 2011 5:38 am
by Live24x7
@maxx99 It solved the problem. You are my genius :D