Page 1 of 1

WHILE loop question - 3 outputs per row

Posted: Fri Feb 24, 2006 7:38 am
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

Posted: Fri Feb 24, 2006 8:35 am
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>";

?>

Posted: Fri Feb 24, 2006 9:17 am
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...

Posted: Fri Feb 24, 2006 9:57 am
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