Page 1 of 1

Displaying data in rows in a table

Posted: Wed Nov 07, 2007 1:58 pm
by gfinney1972
Hi

I'm hoping someone can help as I've hit a brick wall. I've searched sites, googled, tried tutorials, tried borrowing code from tutorials and customising it but I'm no closer to a solution.

Basically I have a database of bands and I want to display a photo of all the bands in a table, I want three columns of images displaying until the MYSQL table reaches its end. ie there is no set number of rows to the table.

Can anybody help me out as I'm losing my mind trying to sort this out..

Cheers


Graham

Posted: Wed Nov 07, 2007 2:04 pm
by Kieran Huggins
try a combination of $i++ and $i % 3 in your loop to test whether it's time for a new row

Posted: Wed Nov 07, 2007 2:07 pm
by gfinney1972
Thanks for your quick response but I'm completely stuck on how to code this.

I can display all my data one after the other but I cannot even begin to understand how to code it into table format..

Posted: Wed Nov 07, 2007 2:08 pm
by gfinney1972
Thanks for your quick response but I'm completely stuck on how to code this.

I can display all my data one after the other but I cannot even begin to understand how to code it into table format..

Loop

Posted: Wed Nov 07, 2007 3:27 pm
by churt
I did not have time to test so if it fails to work let me know and I will troubleshoot it. Hope this helps.

Code: Select all

<?php
//Connect to database and perform query for required data
mysql_connect("host","user","password");
mysql_select_db("dbname");
$query="select * from bands_table";
$result=mysql_query($query);


$ct=1;//Initialize Counter

$ptable="<table>";//Init table variable..ptable is just what I decided to call it...name it whatever you want
//Loop through results
while($row=mysql_fetch_array($result, MYSQL_ASSOC){
   if($ct==1) $ptable.="<tr>";//If $ct==1 Start new row.  Use '.=' to append data to variable
   $ptable.="<td><img src=".$row['imageurl_from_table']."></img></td>";//Display Image
   if($ct==3){ $ptable.="</tr>"; $ct=0; }//After the third image, end row and set $ct=0.  When $ct++ fires it will increment to 1 so that the next row will start properly on the next loop.
   $ct++;//Increment $ct
}
if($ct!==1) $ptable.="</tr>";//If $ct==1 at the end of the loop it meens it ended on a 3, set $ct=0 and incremented $ct to 1.  Therefore no end row would be needed.  Otherwise it is, so we test for $ct not equal to 1.
$ptable.="</table>";//End Table
echo $ptable;//Display Table

?>