Page 1 of 1

display mysql results in threes

Posted: Sun Jul 24, 2011 11:59 pm
by lenswick
okay, so I'm fairly new to MySQL and PHP, but like to think I am a fast learner...
my problem:
I select a number of rows from a MySQL database (let's see fifteen) and want to display them in a table... but I want three results on each row (so it would be a 3x5 table). how do I do that? I know that I can display each result on a new line/row like this:

Code: Select all

$qry = "SELECT * FROM table LIMIT 15";
$rsl = mysql_query($qry, $db) or die(mysql_error($db));
while($row = mysql_fetch_array($rsl)){
echo $row['data'] . "<br />\n";
}
or I can select each piece of data individually - but that would be quite longwinded - there must be an easier way!

Re: display mysql results in threes

Posted: Mon Jul 25, 2011 1:46 am
by kaydeveloper
Try this one
<?php
$qry = "SELECT * FROM table LIMIT 15";
$rsl = mysql_query($qry, $db) or die(mysql_error($db));
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($rsl)){
if($i%3==){
echo "</tr><tr>";
}
echo "<td>".$row['data'] . "</td>";
$i++;
}
echo "</tr></table>';
?>

Re: display mysql results in threes

Posted: Mon Jul 25, 2011 2:16 am
by lenswick
okay, so I think I see how that works... does this part mean if $i is divisible by three?:

Code: Select all

if($i%3==){
it gives a parse error for that line when I try to run it though

Re: display mysql results in threes

Posted: Mon Jul 25, 2011 2:49 am
by lenswick
although, having played with it, I've worked it out.
the way you suggested also added a "<tr></tr>" before the actual output. I've changed it to the following, if you think it can be improved, I'm always looking to improve myself :D

Code: Select all

<?php
include('conn.php');
$qry = "SELECT * FROM table LIMIT 15";
$rsl = mysql_query($qry, $db) or die(mysql_error($db));
echo "<table>\n<tr>";
$i=0;
while($row = mysql_fetch_array($rsl)){
	if(($i%3==0)&&($i != 0)){
		echo "</tr>\n<tr>";
	}
	echo "<td>" . $row['imageID'] . "</td>";
	$i++;
}
echo "</tr>\n</table>";
?>