Colour Key:
- || Page Links
- a. Site Menu
- || Emphasis Only
PHP/MySql Horizontal Looping Recordset
Displaying recordsets horizontally is tricky, but deceptively simple once you hit upon an efficient means. The php method outlined below uses a standard Do-While loop, an if conditional and tables to output the required layout of data.
Lets begin with the recordset; I'll assume you've already established a database connection file with records ready to display.
<?php
//include your db connection file
include('dbConn.php');
mysql_select_db($db_conn, $conn_mySite);
$query = "SELECT * FROM table_name";
$rsRecord = mysql_query($query, $conn_mySite) or die(mysql_error());
$row = mysql_fetch_assoc($rsRecord);
$totalRows = mysql_num_rows($rsRecord);
?>
A standard loop will iterate through the recordset and output the html and record data until all records are displayed. What we're going to do is instantiate a variable '$doHorizontal' before the loop and post-increment it by one each time the loop iterates.
By using a condition whereby $doHorizontal equals the number of 'columns' we want to display horizontally, we can control how many records display across in columns before they iterate down in rows. This is achieved by outputting a table cell for each record and in each loop iteration, opening <tr>'s for the first record, and closing </tr>'s for the last record we want displayed horizontally. Lastly, the $doHorizontal var is reset to 0 for the next table row of records.
Let's take a look at the code...
... NEXT :: Page 1, 2.