How to display products under category [ data grouping ]
I am new to php-mysql. Can somebody help on the issue below? If so, please explain a bit so that I can learn. Thanks in advance.
$data=mysql_query("SELECT tbl_category.*, tbl_product.* FROM tbl_category LEFT JOIN tbl_product ON tbl_category.cat_id=tbl_product.cat_id ORDER BY tbl_category.cat_id");
$color="1";
while($fetch=mysql_fetch_array($data, MYSQL_ASSOC)){
if($fetch['cat_name'] != $category){ //this returns error: "Notice: Undefined variable: category in /.../filename.php on line [this line number]
$catdes = $fetch['pd_description'];
echo "<tr bgcolor='#A9F5F2'><td colspan=\"2\"><div align=\"center\"><br/><b>". $fetch['cat_name']."</b><br /><span class=\"itemdescription\">". $catdes."</div></div></td></tr>";
$category = $fetch['cat_name'];
}
$item = $fetch['pd_name'];
$desc = $fetch['pd_开发者_开发问答description'];
$price = $fetch['pd_price'];
if($color==1){
echo "<tr bgcolor='#FFFFFF'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="2";
}
else{
echo "<tr bgcolor='#F2F2F2'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="1";
}
}
That notice you received is the result of not declaring a variable before using it. It's always good practice to declare your variables before using them.
In your case you need to declare $category
before comparing a value to it:
$category = '';
if($fetch['cat_name'] != $category){
精彩评论