[英]Grouping MySQL Output by Category
我下面的代碼連接到我的數據庫,並按字母順序顯示表中的圖像列表,例如
圖片A,圖片B,圖片C等。
相反,我想按字母順序顯示這些圖像,並按與每個圖像相關的類別進行組織,例如
類別1圖片A,圖片B
類別2圖片C
我還想在每組圖像上方動態顯示每個類別的標題。
我表中的列是:Link_ID,Link_Image,Link_Text,Link_URL,Link_Category
我在這里發現了類似的問題: 輸出MySQL記錄列表,按類別分組? 但我不確定如何使用此實例中給出的解決方案(或顯示動態標題)。
$db_host = 'XXXX';
$db_user = 'XXXX';
$db_pwd = 'XXXX';
$database = 'XXXX';
$table = 'home';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} ORDER BY Link_Text ASC");
if (!$result) {
die("Query to show fields from table failed");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta name="robots" content="noindex">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<style type="text/css">
.linkcontent {
margin: auto;
width: 720px;
height: 714px;
}
.linkcontent a img {
float: left;
margin: 2px;
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
}
.linkcontent a img:hover {
float: left;
border: 2px solid #999;
margin: 0px;
}
.linkcontent_title {
font-family: Arial, Helvetica, sans-serif;
font-size: 24px;
font-weight: normal;
color: #999;
text-align:left;
text-decoration: none;
padding-bottom: 5px;
float: left;
height: 24px;
width: 100%;
clear:right;}
</style>
</head>
<body><div class="linkcontent"><div class="linkcontent_title">Category Title</div>
<?php
while($row = mysql_fetch_array($result))
{?>
<a href="<?php echo $row['Link_URL']?>" ><img src="<?php echo $row['Link_Image']?>" alt="<?php echo $row['Link_Text']?>" width="175" height="175" border="0" /></a>
<?php }?>
</div>
</body>
</html>
<?php
mysql_close ();
?>
首先,更改查詢,以便按Link_Category
排序結果,然后按Link_Text
。
SELECT * FROM {$table} ORDER BY Link_Category ASC, Link_Text ASC
然后,當您循環搜索結果時,將您的<div class="linkcontent_title">Category Title</div>
放入循環中。 要在類別更改時更改Link_Category
,只需使用存儲當前類別的簡單php var,即。 $currentCategory
<body>
<?php
$currentCategory = ""; //use this to change the Category Title
while($row = mysql_fetch_array($result))
{
if($row['Link_Category'] != $currentCategory) // was wrong on the first draft
{
if($currentCategory != "") //if this is not the 1st, close the last <div>
{ ?>
</div>
<?php } // ends not 1st Category Title if{} ?>
<div class="linkcontent">
<div class="linkcontent_title"><?php echo $row['Link_Category']?></div>
<?php $currentCategory = $row['Link_Category']; //Set the Current Category
} // ends the Category Title if{} ?>
<a href="<?php echo $row['Link_URL']?>" >
<img src="<?php echo $row['Link_Image']?>" alt="<?php echo $row['Link_Text']?>" width="175" height="175" border="0" />
</a>
<?php }?>
</div>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.