mysql / while loop

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
unplugged
Forum Newbie
Posts: 1
Joined: Wed Jun 24, 2009 10:57 am

mysql / while loop

Post by unplugged »

I have a mysql database with several rows. The row contains an image URL and other data.

I want to display 5 images in each row, then create another row if more images exist after the first 5.

After 3 rows, I want to have a link at the bottom to choose (previous/next page) to sift thru it all.

I'm familiar with mysql but not too much with PHP as far as doing something like this. Any help is appreciated.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: mysql / while loop

Post by jayshields »

You'll want to use a LIMIT clause on your query to fetch 15 rows at a time. Then when outputting the images in a loop in PHP, use the modulus operator (%) to see if the current loop iterator % 5 is 0, if it is, end the row and start a new one. Something like:

Code: Select all

$x = 1;
echo '<table><tr>';
while($row = mysql_fetch_assoc($result))
{
  echo '<td><img src="' . $row['whatever'] . '" /></td>';
  if($x % 5 == 0) echo '</tr><tr>';
  $x++;
}
echo '</tr></table>';
In regards to the next/previous page thing, you need to look into "pagination".
Post Reply