Jump to content

[SOLVED] This should be easy: checking whether a number is whole


DaveLinger

Recommended Posts

So basically I'm writing a quick-and-dirty script to read all of the items from a database, and display them in a table. I think the easiest way to accomplish this is to display each result, then check if the result number plus one divided by 3 is a whole number (for a 3 column table), and if it is, echo </tr><tr>.

 

So here's what I'm thinking (looping per result of course). I'm adding one to the result number so that 0 becomes 1, and so on.

 


echo "<td>this is some database info</td>";

$newresultnumber = $resultnumber+1;

if($newresultnumber ??? is a whole number ???){echo "</tr><tr>";}

^^loop

 

So what can I do to make this work?

use the Modulo (%) it will return the remainder of a division equation so 1%3 returns 1 because 1 is the remainder of 1/3

but it will return 0 on 3%3 or 6%3

so you can have a database query script like

for($i = 1;$row = mysql_fetch_row($result);$i++){
    echo "<td>{$row[1]}</td>";
    if($i%3 == 0){
        echo "</tr><tr>";
    }
}

 

Scott.

How would I make it so that if it's the last result, it does NOT do this? I can close the tr and the table outside of the loop, but it's no good if it opens a new tr that I'll just have to immediately close at the end.

My final code (for others' reference):

 

	$totalrows = mysql_num_rows($result);

if($totalrows >0){
for($i = 1;$row = mysql_fetch_row($result);$i++){

echo "<td><a href=\"game.php?id={$row[0]}\"><img src=\"images/games/thumbs/{$row[0]}_t.png\" alt=\"{$row[2]}\"><br />{$row[2]}</a></td>";

if($i%3 == 0 && $i != $totalrows){echo "</tr><tr>";}

	if($i == $totalrows && $i%3 != 0){

	$i1 = $i+1;
	if($i1%3 == 0){echo "<td> </td>";}
	$i2 = $i+2;
	if($i2%3 == 0){echo "<td> </td><td> </td>";}

	}

}

}else{

echo "<p>No results found!</p>";
}

 

As you can see I made it add enough blank cells after the last row to even out the table.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.