Jump to content

Looping MySQL Results into multicolumn table


sford999

Recommended Posts

This is probably really simple, but I can't for the life of me figure it out.

 

What I`m trying to do is have a table with 3 columns and output say category ID 1 into column 1, Cat ID 2 into column 2 etc... from a list of categories in a mysql database (done so that any new categories can be added without having to do file edits)

 

| Column 1 ||Column 2 || Column3 |

|  Cat ID 1 || Cat ID 2 || Cat ID 3 |

|  Cat ID 4 || Cat ID 5 || Cat ID 6 |

 

Each CAT ID will be linked to another section displaying a list of items in that category. eg <a href="category.html?1">Cat 1</a>

 

I would appreciate some help on this.

 

Thanks

I use this for multiple columns that are determined by the number of entries. Modify the HTML output a bit to suit your column headings and it should work. The references to the links, of course, would need to be modified as well:

 

// run query
$sql = "SELECT * FROM subcategories WHERE cat_id='2'";
$results = mysql_query($sql) or die(mysql_error());
// display results
$totalColumns = 2;
$i = 1;
echo "<table border='0' cellpadding='2'>";
while ($row = mysql_fetch_array($results)){
if ($i == 1) echo "<tr>";
echo "<td>";
echo "<a href='getcat.php?subcat_id=". $row['subcat_id'] . "'>" . $row['subcat_name'] . "</a>";
echo "</td>";
if ($i == $totalColumns)
	{
	echo "</tr>";
	$i = 0;
	}
$i++;
}
echo "</table>";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.