How do I display query results in an N-column table layout?
Displaying query information in a N-column table can be done with just a bit of logic. This first bit of code just creates a query object for the example, you don't need this if you have your own data to work with.
<cfscript>
stateList = "Alabama,Alaska,Arizona,Arkansas,California,Colorado,Connecticut,Delaware,Florida,Georgia,Hawaii,Idaho,Illinois,Indiana,Iowa,Kansas,Kentucky,Louisiana,Maine,Maryland,Massachusetts,Michigan,Minnesota,Mississippi,Missouri,Montana,Nebraska,Nevada,New Hampshire,New Jersey,New Mexico,New York,North Carolina,North Dakota,Ohio,Oklahoma,Oregon,Pennsylvania,Rhode Island,South Carolina,South Dakota,Tennessee,Texas,Utah,Vermont,Virginia,Washington,West Virginia,Wisconsin,Wyoming";
myQuery = QueryNew("stateName");
for(i=1;i LTE ListLen(stateList);i = i + 1) {
queryAddRow(myQuery);
querySetCell(myQuery,"stateName",ListGetAt(stateList,i));
}
</cfscript>
Here is where you set the number of columns you want your data to be outputted in, you can adjust it very easily:
<!--- adjust the number of columns to your needs --->
<cfset columnCount = 4>
Finally the table output:
<table border="1">
<tr>
<cfoutput query="myQuery">
<td>#stateName#</td>
<cfif currentRow MOD columnCount EQ false AND currentRow NEQ recordCount>
</tr>
<tr>
<cfelseif currentRow MOD columnCount EQ false AND currentRow EQ recordCount>
</tr>
<cfelseif currentRow MOD columnCount AND currentRow EQ recordCount>
<cfset columnsLeft = (Ceiling(currentRow/columnCount)*columnCount) - currentRow>
#RepeatString("<td> </td>",columnsLeft)#
</tr>
</cfif>
</cfoutput>
</table>
Basically the main thing going on here is math, specifically, determining if we have completed a "row" based on our current query row and the number of columns we specified. Note at the end we "fill" the table with blank cells. This completes our table and will help it render properly.
This question was written by Erik Goodlad
It was last updated on February 22, 2006.