'while' not working as expected

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
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

'while' not working as expected

Post by IGGt »

Hi Guys,

I have a script that gets a MySQL result consisting of an ID field (1-25) and a colour.

I then put those into a html table. I am trying to get a situation whereby ID's 1-5 are a row (<tr>), then I start a new row (</tr><tr>) at ID 6. (and going forward also row 11,16,21). But at present it doesn't work. It seems to be assigning 6 as every ID, and so it is creating a new row at each stage.

Code: Select all

$result = mysql_query("SELECT `id`, `colour` FROM `db1`.`squares` ORDER BY `id` ASC");

echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array($result)) {
        							if($row['id'] = 6) {
	        									echo '</tr><tr>';
        										}
        echo '<td bgcolor=' . $row['colour'] . '>'.$row['id'].'</td>';
}

</tr>
</table>
As you can see I have put the $row['id'] in each table field (<td>) to see what it is returning.

Any ideas as to why it is returning 6 for every result, and not the ID as per the MySQL statement?
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: 'while' not working as expected

Post by mikosiko »

IGGt wrote:.....
while($row = mysql_fetch_array($result)) {
if($row['id'] = 6) {
echo '</tr><tr>';
}
echo '<td bgcolor=' . $row['colour'] . '>'.$row['id'].'</td>';
}

</tr>
</table>
[/syntax]

As you can see I have put the $row['id'] in each table field (<td>) to see what it is returning.

Any ideas as to why it is returning 6 for every result, and not the ID as per the MySQL statement?
try this

Code: Select all

while($row = mysql_fetch_array($result)) {
        echo '<td bgcolor=' . $row['colour'] . '>'.$row['id'].'</td>';
        if (!($row['id'] % 5)) {
            echo '</tr><tr>';
        }
}
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: 'while' not working as expected

Post by IGGt »

That's great, fixed both problems in one go.

cheers.
Post Reply