It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming PHP and MySQL Forum

PHP loop through database and limit number of entries

Moderator: Malcolm

PHP loop through database and limit number of entries

Postby gilbertsavier on Fri Jul 31, 2009 9:51 am

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>";


}
gilbertsavier
 
Posts: 24
Joined: Fri Jun 26, 2009 11:34 am

Re: PHP loop through database and limit number of entries

Postby rse on Tue Aug 11, 2009 6:42 am

I would do something like this:

Code: Select all
$x = 0; // Integer to count column

$result = mysql_query($query);

while($data = mysql_fetch_array($result) {
if($x == 0) { echo "<tr>\n"';} // Create new row

echo "<td>".$data['fieldname']."</td>"; // Output data

$x++; // Adds 1 to column count

if($x == 3) {
echo "</tr>\n"; // Close off row after third entry
$x = 0; }
}


So essentially the column count resets itself after ever third entry so it loops round correctly.

I hope this helps.

Ads :)
Adam Williams
PHP Web Developer

Personal: http://30things.net
Blog: http://www.root-servers.co.uk
User avatar
rse
100+ Club
 
Posts: 141
Joined: Sun Oct 10, 2004 8:15 pm
Location: Leeds, UK


Who is online

Users browsing this forum: No registered users and 0 guests