我試圖想出一種有效的方式來顯示一些數據,但沒有成功。使用php交叉製表查詢
該表是動態地從幾桌建,以顯示與填充顯示結果通過網站如列標題的行:
Site name | Column A | Column B | Column C => column headers continue from DB query
Site A | Result A | Result B | Result C
Site B | Result C | Result B | Result C
Site C | Result C | Result B | Result C
Results keep going vertically.
下面是我使用
$risk_section=$row_risk_category['risksectid'];
mysql_select_db($database_auditing, $auditing);
$qry_selfsites = sprintf("SELECT
tblself.siteid AS selfsite,
tblsite.sitename AS sitename,
tblsite.address AS address,
tblpct.pctname AS pctname,
tblresultsnew.total,
tblresultsnew.auditid AS auditid,
tblriskcategories.risksectid AS risksectid,
tblriskcategories.risksection AS risksection
FROM tblself
LEFT JOIN tblresultsnew ON tblself.auditid = tblresultsnew.auditid
LEFT JOIN tblsite ON tblself.siteid = tblsite.siteid
LEFT JOIN tblpct ON tblsite.pctid = tblpct.pctid
LEFT JOIN tblriskcategories ON
tblresultsnew.risksectid=tblriskcategories.risksectid
WHERE tblsite.pctid IN (SELECT pctid FROM tblreportpcts WHERE
pctreportid='$pctreportid')
AND tblsite.sitetypeid IN (SELECT sitetypeid FROM tblreportsites WHERE
pctreportid='$pctreportid')
AND tblself.year = %s
ORDER BY tblsite.pctid,tblsite.sitename",
GetSQLValueString($yearofrpt, "int"));
$selfsites = mysql_query($qry_selfsites, $auditing) or die(mysql_error());
$totalRows_selfsites = mysql_num_rows($selfsites);
查詢
所以問題是,有沒有辦法從上述查詢(或其修改後的版本)中獲取數據來動態構建表格,並使所有結果正確排列?到目前爲止,我只能讓它垂直構建。
對不起,編輯時間(已與下面的答案的工作,我意識到我沒有措辭得到了很好的問題)
我想要得到的是從查詢列標題的行( tblriskcategories.risksection AS risksection
)這些水平填充列名稱。
然後下方,網站名稱,顯示與對應於列標題以上即
<table>
<tr>
<th>Sitename</th>
<?php while($row_selfsites=mysql_fetch_assoc($selfsites){
//loop through the section headers pulled from the DB (tblriskcategories)
<th><?php echo $row_selfsites['risksection'];//show the section headers?></th>
<?php }
//end header loop then start another loop to show a row for each site pulled
//out by the query and show the relevant results in the correct column
while($row_selfsites=mysql_fetch_assoc($selfsites)) {
//do the vertical drop matching the header rows with the sitenames from tblsite
//and the results from tblresultsnew
?>
<tr>
<td><?php echo $row_selfsites['sitename'];?></td>
<td><?php echo $row_selfsites['total'];
//these need to grow to fit the headers and each site?></td>
<tr>
<?php } //end displayed data loop?>
</table>
下相關的表結構的結果:
tblresultsnew resultsid,auditid,risksectid,總
tblriskcategories risksectid,risksection
tblself selfauditid,SITEID,auditid
tblsite SITEID,站點名
因此,tblself擁有我們需要的數據和相關auditid的站點列表,
tblresultsnew保存結果 - 總列 - 每個risksectid和每個auditid,例如,一個auditid可以具有大約8個risksectid,每個具有相應的總數
tblriskcategories擁有列標題
tblsite擁有網站數據,使其意味着
我希望這可以進一步解釋這個問題。
再次感謝您的幫助。
戴夫
您可以添加一個最終結果表應該是什麼樣子的例子,還是問題中提出的表格是什麼樣的,問題是「我如何使它看起來像這樣」? – newfurniturey 2012-07-16 19:23:04
你能通過http://sqlfiddle.com/提供示例輸入嗎? – MvG 2012-07-16 19:47:52
嗨,原始問題中的桌子幾乎看起來如何 - 我看到它的方式(至少在我的頭上)是用兩個while循環構建它 - 一個填充水平標題 – 2012-07-16 20:21:04