output results in two columns

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
andrei.mita
Forum Commoner
Posts: 65
Joined: Sun May 08, 2005 4:06 am
Location: Barlad/Romania

output results in two columns

Post by andrei.mita »

I run a query on a db and I want to output the results in two or more columns but I don't know to make the output stop at half way and step into the next column.
I use this

Code: Select all

$break = mysql_num_rows($result)/2;
but how to i make the for or the while start the output in the second column from $break+1 ??
R0d Longfella
Forum Newbie
Posts: 20
Joined: Fri Apr 08, 2005 7:17 am

Post by R0d Longfella »

Just for the fun of it

Code: Select all

$rows = 40;
$break = $rows / 2
print ("<table>\n");
print ("<tr><td>\n");
for ($i = 0; $i < $rows; ++$i) {
  if ($i == $break) {
    print "</td><td>\n";
  }
  print ("Results\n");
}
print ("</td></tr>\n");
print ("</table>\n");
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

or if you're doing it in a while as you suggested, just set a counter before you start the loop and as soon as the counter hits the ($rows / 2) marker, start your new col.
andrei.mita
Forum Commoner
Posts: 65
Joined: Sun May 08, 2005 4:06 am
Location: Barlad/Romania

Post by andrei.mita »

thanks
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

Post by MathewByrne »

I did something similar a while ago, a little more flexible though and allows you do define how many columns you want:

Code: Select all

// Loop though all the returned rows and format results
define("NUM_COLS", 2);
$numRows = 40;
$finalRows = ceil($numRows / NUM_COLS)
$colWidth = floor(100 / NUM_COLS);

echo "\n<table width='100%'>\n\t<tr>";
for($i = 0; $i < NUM_COLS; $i++) { 
	echo "\n\t\t<td width='".$colWidth."%'>
			<table width='100%'>
				<tr>
					<td>Column Header</td>
				</tr>";
	for ($j = 0; $j < $finalRows; $j++) {
		if($row = mysql_fetch_array($result)) {
			echo "\n\t\t\t\t<tr>"
			   . "\n\t\t\t\t\t<td>Information</td>"
			   . "\n\t\t\t\t</tr>";
		}
		else {
			echo "\n\t\t\t\t<tr>";
			   . "\n\t\t\t\t\t<td colspan=\"3\">&nbsp;</td>"
			   . "\n\t\t\t\t</tr>";
		}
	}
	echo "\n\t\t\t</table>\]n\t\t</td>";
}
echo "\n\t</tr>\n</table>";
Sorry if it's a bit messy, I took it a bit out of context.
andrei.mita
Forum Commoner
Posts: 65
Joined: Sun May 08, 2005 4:06 am
Location: Barlad/Romania

Post by andrei.mita »

thanks, i'll try and short it out
Post Reply