Hi, I’m just getting up to speed with creating tables using PHP/MySql. I’ve read Larry Ullman’s book, which is great but I’m stuck on something.

I want to be able to create a table that has 3 columns and multiple rows.

For example, say I have a one column MySql table with the values ‘one’ through to ‘six’. I would like my HTML table to look like this:

<table>
<tr>
<td>one</td><td>two</td><td>three</td>
</tr>
<tr>
<td>four</td><td>five</td><td>six</td>
</tr>
</table>

Here is what I have so far in PHP:

$query = "select * from photos";
$result = mysql_query($query);

echo "<html><head></head><body>
<table>";

if ($result) {
while ($row = mysql_fetch_array($result)) {
echo 
"<tr>".
"<td>".$row['filename']."</td>".
"<td>".$row['filename']."</td>".
"<td>".$row['filename']."</td>".
"</tr>";
}
mysql_free_result($result);
} else {
echo mysql_error();
}
mysql_close();
echo "</table>"
?>

I see what my problem is – that the ‘filename’ won’t increment because is it still in the same loop and my result looks like this:

<html><head></head><body>
<table>
<tr>
<td>one</td><td>one</td><td>one</td>
</tr>
<tr>
<td>two</td><td>two</td><td>two</td>
</tr>
<tr>
<td>three</td><td>three</td><td>three</td>
</tr>
<tr>
<td>four</td><td>four</td><td>four</td>
</tr>
<tr>
<td>five</td><td>five</td><td>five</td>
</tr>
</table></body></html>

Any ideas how I can do this?

Thanks a lot!

Peter.

    petermcphee check the code below, I believe it´s the same thing you want

    That code lists a mysql database user list into tables with $num_columns columns and $num_rows of rows. So you can change those variables

    😃

    <?
    
    $result = mysql_query("select *  from users where active = 1");
    
    echo "<html><head></head><body> 
    <table>"; 
    
    $num_columns = 3;
    $num_rows = mysql_num_rows($result);
    $i=0;
    while($row = mysql_fetch_assoc($result)){
    	$results[$i] = $row['name'];
    	$i++;
    }
    unset($i);
    $k=0;
    for ($i=0;$i<=($num_rows/($num_columns+1));$i++){
    	echo '<tr>';
    
    for($j=1;$j<=$num_columns;$j++){
    	echo '<td>'.$k.' - '.$results[$k].'</td>';
    	$k++;
    }
    
    echo '</tr>';
    $k++;
    }
    echo "</table></body>
    </html>"
    ?>
    
    
    

      Hi Dimc/Weedpacket, thanks for the info...much appreciated. I will go over those posts and try it out.

      Thanks again!

      Peter.

        Write a Reply...