The Most Active and Friendliest
Affiliate Marketing Community Online!

“AdsEmpire”/  Direct Affiliate

PHP loop through database and limit number of entries

gilbertsavier

New Member
affiliate
Hi,
Going to try to explain this as best I can. I have a bunch of stuff in a database and I need to display this info within a table. This isn't a problem at all but, I need it to only display 3 td tags per line and then move on to the row.

so i need it to do :

code:

<table>
<tr>
<td>My First Row</td>
<td>My First Row 2</td>
<td>My First Row 3</td>
</tr>

<tr>
<td>My Second Row</td>
<td>My Second Row 2</td>
<td>My Second Row 3</td>
</tr>
</table>



and continue to do this through every entry in the database table.

so I have something like this that will display the info:

code:

for ($i = 1; $i <= $num; $i++){

$chairArray = mysql_fetch_array($chairResult);
$chairName = $chairArray['name'];
$chairDescription = $chairArray['description'];
$chairImage = $chairArray['image'];

echo "<tr>";
echo "<td>";
echo "<img src=\"images/catalog/ottomans/thumbs/$chairImage\" width=\"157\" height=\"147\" />";
echo "<br />";
echo $chairName;
echo "</td>";
echo "</tr>";


}
 
Hiya,

I am not saying this is the best way. I am still learning php myself. But I think something along the lines of this may help?

Code:
<?php
	
	$count = 0;
	echo 'open td<br>';
	for($i=0;$i<15;$i++)
	{
		$count++;
		if($count == 0)
		{
			echo 'open td<br>';
		}
		else if($count > 3)
		{
			echo 'close td<br>';
			echo 'open td<br>';
			$count = 0;
		}
		else
		{
			echo 'content<br>';
		}
	}
	echo 'close td<br>';

?>

Like I say, this may be totally useless. I was just trying to create a loop that would do like you wanted.

- Methok
 
Code:
<?php
    
    $count = 0;
    echo 'open td<br>';
    for($i=0;$i<15;$i++)
    {
        $count++;
        if($count == 0)
        {
            echo 'open td<br>';
        }
        else if($count % 3==0)
        {
            echo 'close td<br>';
            echo 'open td<br>';
        }
    }
    echo 'close td<br>';

?>

The best way to do it is with the modulo division operator ('%') - this way you don't have to keep resetting $count to zero every time it gets to 3 - simply divide the count by 3 and if the remainder is 0, do a new row.

PHP: Arithmetic Operators - Manual
 
MI
Back