WHILE loop question - 3 outputs per row

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
michlcamp
Forum Commoner
Posts: 78
Joined: Mon Jul 18, 2005 11:06 pm

WHILE loop question - 3 outputs per row

Post by michlcamp »

This is probably one of those questions that's been answered a thousand times on the forum -

How do I write a WHILE loop that displays table info (in this case, graphics) 3 per row..

for instance, if I have ten graphics in a table, I want to display pictures - three rows of 3 and one row of 1

Code: Select all

echo "<tr><td>graphic1</td><td>graphic2</td><td>graphic3</td></tr>";
for however many rows there are...

all help appreciated in advance..
thanks.mc
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

<?php

$result = mysql_query('SELECT * FROM `table`');

echo "<table>\n<tr>";
while ($row = mysql_fetch_assoc($result)) {
    echo "<td>{$row['column1']}</td><td>{$row['column2']}</td><td>{$row['column3']}</td>";
}
echo "</tr>\n</table>";

?>
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

Code: Select all

//Start the table
echo '<table border="1" bordercolor="black">';

//Initialise some variables to help with printing the table
$rowmax = 2;
$x = 0;

//Read all the files from the directory and print them all in the table
if ($handle = opendir('gallery/')) {
   while (false !== ($file = readdir($handle))) {
       if ($file != "." && $file != ".." && $file != "Thumbs.db") {
			if ($x % $rowmax == 0) {
				echo '<tr>';
			}
			echo '<td><center><a href="gallery/' . $file . '"><img src="gallery/' . $file . '" border="0"></a><br><i>' . $file . '</i></center></td>';
			
			if ($x % $rowmax == $rowmax - 1) {
				echo '</tr>';
			}
			$x++;
		}
   }
   closedir($handle);
}

//Close the table
echo '</table>';
This is something I've used before, I'm sure you can modify it to your needs :)

Edit: I've just read it back, the $rowmax variable should really be $colmax, as that variable defines how many columns should be in the table, it has nothing to do with rows... I must of been half asleep coding that...
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

This question has been asked quite a bit. Feyd put together a collection of posts that answer common questions like this. I believe it is under the PHP Code Forum. The topic title is Usefel Posts.

viewtopic.php?t=29816
Post Reply