Multicolumn Output from a Database with PHP - Vertical Display
(Page 3 of 4 )
OK, now let's do a vertical display. Let's take a look at our new code.
<?php $columns = 4;
mysql_connect('localhost','',''); mysql_select_db('test'); $query = "SELECT stuff FROM mystuff ORDER BY stuff"; $result = mysql_query($query);
$num_rows = mysql_num_rows($result);
//we are going to set a new variables called $rows $rows = ceil($num_rows / $columns);
//to do this display, we will need to run another loop //this loop will populate an array with all our values while($row = mysql_fetch_array($result)) { $data[] = $row['stuff']; }
echo "<TABLE BORDER=\"0\">\n";
//here we changed the condition to $i < $rows for($i = 0; $i < $rows; $i++) {
echo "<TR>\n"; //here will run another loop for the amount of columns for($j = 0; $j < $columns; $j++) { if(isset($data[$i + ($j * $rows)])) { echo "<TD>" . $data[$i + ($j * $rows)] . "</TD>\n"; } } echo "</TR>\n"; } echo "</TABLE>\n"; ?> |
OK, let's take a look at the modifications one by one.
$rows = ceil($num_rows / $columns); |
We have set a new variable called $rows. We get this value from the number of rows in our data set divided by the number of columns we want. The ceil function rounds that number up to the next whole number.
while($row = mysql_fetch_array($result)) { $data[] = $row['stuff']; } |
Next we take all the data from the result set and put it in an array.
for($i = 0; $i < $rows; $i++) { |
Or for loop condition changed to only loop for the number of rows we will need.
for($j = 0; $j < $columns; $j++) { if(isset($data[$i + ($j * $rows)])) { echo "<TD>" . $data[$i + ($j * $rows)] . "</TD>\n"; } } |
Here is what does the magic. What we are doing here is running a for loop for the amount of columns we want. Then we take which column we are on (0, 1, or 2) and multiply that times the amount of rows in our table. Then we add that the the row we are on to get which piece of data to display.
As you can see, we no longer need to check whether or not to display the start and end of a row, we always do as the outer for loop is on a per row basis.
Next: Something to think about >>
More Database Articles Articles
More By Matt Wade