2012-12-05 15 views
3

我想在PHP/HTML表中顯示像這樣的MySQL結果。也許爲每個工廠添加鼠標信息,如果這很容易的話。將SQL結果分類並顯示在表中PhP

 
+-----------------------------------------------------------+ 
|category1 ¦ category2 ¦ category3 ¦ category4 ¦ category5 ¦ 
+-----------+-----------+-----------+-----------+-----------+ 
| plantName ¦ plantName ¦ plantName ¦ plantName ¦ plantName ¦ 
| plantName ¦ plantName ¦ plantName ¦ plantName ¦ plantName ¦ 
| plantName ¦ plantName ¦   ¦   ¦   ¦ 
|   ¦ plantName ¦   ¦   ¦   ¦ 
|   ¦ plantName ¦   ¦   ¦   ¦ 
+-----------+-----------+-----------+-----------+-----------+ 

首先,我通過海拔和降雨值來選擇植物。

$sql = mysql_query("SELECT * FROM `plants_tb` 
WHERE $elevate>= elevationLOW && $elevate<= elevationHI && 
$rainfall>= rainfallLOW && $rainfall<= rainfallHI ORDER BY commonNames ASC"); 

$plant = 'commonNames'; 
$elevationH = 'elevationHI'; 
$elevationL ='elevationLOW'; 
$rainfallL ='rainfallLOW'; 
$rainfallH ='rainfallHI'; 
$species ='species'; 

echo "<table border='1'><tr><th>Name</th><th>Category</th></tr>"; 
while($row = mysql_fetch_array($sql)){ 
echo "<tr><td>" . $row[$plant] . "</td><td>" . $row['heightHI'] . "</td></tr>"; 
} 
echo "</table>"; 

現在我需要按高度類別在列中顯示它們。也許我應該創建一個選定植物的臨時表格,然後對它們進行分類,然後將它們顯示在列中? 這是我的分類想法。我知道這段代碼之間的關係不正確,但它讓我明白了。

$sql="SELECT tree_height FROM $Elevation_Rainfall_list; 
WHERE tree_height 
BETWEEN 1 AND 7 = $Category1 
BETWEEN 7 AND 15 = $Category2 
BETWEEN 15 AND 30 = $Category3 
BETWEEN 30 AND 9999 = $Category4 
if not = $Category5 

mahalo的支持!

回答

3

看起來像你想創建一個像直方圖一樣。

,而不是試圖分類的SQL查詢的數據,你應該是這樣做在PHP:

$histogram = array(); 
# classify the data into histogram bins 
while($row = mysql_fetch_array($sql)) { 
    $h = $row['tree_height']; 
    $cat = 3; 
    if ($h <= 7) { 
     $cat = 0; 
    } elseif ($h <= 15) { 
     $cat = 1; 
    } elseif ($h <= 30) { 
     $cat = 2; 
    } 
    $histogram[$cat][] = $row['commonNames']; 
} 

# determine the number of rows in the table 
$rows = 0; 
foreach ($histogram as $ar) { $rows = max($rows, count($ar)); } 

# write a table with the data 
echo "<table border='1'>\n" . 
    " <tr>\n <td>Category 1</td>\n <td>Category 2</td>\n" . 
    " <td>Category 3</td>\n <td>Category 4</td>\n</tr>\n"; 
for ($i = 0; $i < $rows; ++$i) { 
    echo " <tr>\n"; 
    for ($cat = 0; $cat <= 3; ++$cat) { 
     echo " <td>" . $histogram[$cat][$i] . "</td>\n"; 
    } 
    echo " </tr>\n"; 
} 
echo "</table>\n"; 
+0

+1直方圖比喻:) – andr

+0

首先馬洛用於該項目的投入。我沒有正確使用你的代碼。我只是得到一個空白頁面。我正在調試,我發現, 致命錯誤:134217728字節允許的內存大小已耗盡(嘗試分配71個字節)在行62' '$ histogram [$ cat] [] = $ row [$植物];' 也許這個while循環卡住? 'while($ row = mysql_fetch_array($ sql))' – Kaleo10

+0

這個循環應該沒問題,因爲mysql_fetch_array在沒有更多行需要讀取時返回null(其結果爲false)。你的數據庫更有可能有很多記錄,你需要更多的內存來處理它們。結果中有多少行?把'echo mysql_num_rows($ sql)'放在你的查詢之後的地方找出來。 –