Strange Problem when using while with mysql_fetch_assoc

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
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Strange Problem when using while with mysql_fetch_assoc

Post 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 ?
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Strange Problem when using while with mysql_fetch_assoc

Post 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.
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Strange Problem when using while with mysql_fetch_assoc

Post by Live24x7 »

thanks Mcinfo.. So what is the correct way to display the entire list without skipping anything ?
maxx99
Forum Contributor
Posts: 142
Joined: Mon Nov 21, 2011 3:40 am

Re: Strange Problem when using while with mysql_fetch_assoc

Post 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 :)
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Strange Problem when using while with mysql_fetch_assoc

Post by Live24x7 »

@maxx99 It solved the problem. You are my genius :D
Post Reply