Finally got this working as it should!
This is the code now
<?php
include 'connect.php';
$q = "SELECT c.category, c.cat_id,GROUP_CONCAT(s.subcat_id,'|', s.subcategory ) AS sublist FROM categories AS c
LEFT JOIN subcategories AS s ON c.cat_id = s.cat_id";
if(isset($_GET['subcat_id'])) $q .= " WHERE s.cat_id=".$_GET['subcat_id'];
$q .=" GROUP BY c.cat_id ORDER BY c.cat_id";
$r = mysql_query($q) or die( 'Could not execute query: ' . mysql_error() );
$output = '<ul id="nav">';
while($data = mysql_fetch_array($r)){
$output .= "<li><a href={$data['cat_id']} class='category'>{$data['category']}</a>";
if(!empty($data['sublist'])){
$subcats = explode(",", $data['sublist']);
$output .="<ul>";
foreach ($subcats as $pair) {
list($subcat_id, $subcategory) = explode('|', $pair);
// output link
$output .= "<li><a href=$subcat_id class='subcategory'>$subcategory</a></li>";
}
$output .= "</ul>";
}
$output .="</li>";
}
$output .= '</ul>';
echo $output;
?>
Thanks to all who replied..................