yoda69 Posted April 6, 2010 Share Posted April 6, 2010 Hi, I have a table with a 100 rows. I want to create an "if statement" that create a table with 10 cells for every table row. Can you guys suggest a way of doing so. This is what I got so far. <html> <head> </head> <body> <div id="container"> <form method="get"> <table> <tr> <?php $db = mysql_connect("xxx","xxx","xxx") or die("Problem connecting"); mysql_select_db("xxx") or die("Problem selecting database"); $sql = "SELECT * FROM cells;"; echo $sql; $result = mysql_query($sql) or die ("Query failed"); $numofrows = mysql_num_rows($result); for($i = 0; $i < $numofrows; $i++) { $row = mysql_fetch_array($result); //get a row from our result set $background = $row[color]; echo "<td id=\"cell\"><a id=\"test\" style=\"background:#".$background."\" href=\"http://www.xxx.com/CColor.php?cell=1\"></a></td>\n"; } echo "</tr>"; ?> </table> </form> </div> </body> </html> Thanks! Link to comment https://forums.phpfreaks.com/topic/197771-if-statement-for-a-table/ Share on other sites More sharing options...
Chris92 Posted April 6, 2010 Share Posted April 6, 2010 Put this at the bottom of your for loop. $x++; if( $x == 10 ) { echo " </tr> <tr>\n"; $x = 0; } Please define $x before your loop. Link to comment https://forums.phpfreaks.com/topic/197771-if-statement-for-a-table/#findComment-1037876 Share on other sites More sharing options...
seniramsu Posted April 6, 2010 Share Posted April 6, 2010 I would cut out the query to get the number of rows and instead do something like this... using a while loop: $query = "SELECT * FROM `database`.`cells`"; $result = mysql_query($query, $connection); while (isset($result)) { // as long as the query returns a result, then execute while loop: $row = mysql_fetch_assoc($result); // put your queried data into an easy to use array $id = $row['id']; // set variables for the data returned in your mysql_fetch_assoc to whatever your database column names are. // (ie. 'cells', 'id', etc.). if (isset($id)) { //if condition within your while loop. Give the data in your database auto incrementing ids // echo a table with your 10 cells echo "<table id=\"table_for_your_stuff\"> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> <td>Cell 4</td> <td>Cell 5</td> <td>Cell 6</td> <td>Cell 7</td> <td>Cell 8</td> <td>Cell 9</td> <td>Cell 10</td> </tr> </table>"; // you could also perform more php within each cell (for instance if you want to // call data from the database and have it return a value to a specific cell...) if (!isset($id)) { // once your while loop reaches the last id in the table, the while loop will exit. Important, so it doesn't loop forever. exit; } } Worked well for me, I just had to do the same for a project of mine. Link to comment https://forums.phpfreaks.com/topic/197771-if-statement-for-a-table/#findComment-1037969 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.