2012-07-25 173 views
0

我一直在試圖弄清楚如何創建一個從數據庫中填充過去幾天的treeview,現在使用我已經遇到但迄今尚未成功的各種示例。Treeview從數據庫填充

我的數據庫的結構是: ID | parent_id |標題|緊迫性(緊急性尚未實施)

最終結果應該生成一個樹狀視圖,其中緊迫性的值指示用於每個項目的圖像。

我一直在試圖利用最近的代碼是:

<hmtl> 
<body> 
<?php 

function get_children($parent, $level = 1) 
{ 
$result = mysql_query('SELECT * FROM treeview_items WHERE parent_id = '.$parent); 
$result2 = mysql_fetch_array($result, MYSQL_ASSOC); 
#for avoiding some errors 
if(mysql_num_rows($result) > 0) 
    #start the list 
    echo '<ul>'; 
    foreach($result2 as $row) { 
     #print the item, you can also make links out of these 
     echo '<li>'.$row['title'].'</li>'; 
     #this is similar to our last code 
     #this function calls it self, so its recursive 
     get_children($row['id'], $level+1); 
    } 
    #close the list 
echo '</ul>'; 
} 

mysql_connect('localhost', 'root'); 
mysql_select_db('test'); 

$result = mysql_query('SELECT * FROM treeview_items'); 
$result2 = mysql_fetch_array($result, MYSQL_ASSOC); 

#for avoiding some errors 
if(mysql_num_rows($result) > 0) { 
#start the list 
echo '<ul>'; 
foreach($result2 as $row) { 
    #print the item, you can also make links out of these 
    echo '<li>'.$row['title'].'</li>'; 
    #recursive function(made in next step) for getting all the subs by passing 
id of main item 
    get_children($row['id']); 
} 
#end the list 
echo '</ul>'; 
#some message if the database is empty 
} 
else echo 'No Items'; 

#clear the memory 
mysql_free_result($result); 
?> 
</body> 
<html> 

基本上我的代碼不能正常工作,所以我希望有人能夠給我一個手來解決這個問題。任何幫助是極大的讚賞! :)

編輯

我改變了一些代碼來修復了幾個錯誤 的所以現在我所看到的是:

警告:爲第13行的C:\ Program Files \ EasyPHP-5.3.9 \ www \ test.php中的foreach()提供的無效參數

重複100次,直到它中止。不知道爲什麼,因爲代碼中的兩個foreach()都是一樣的,但函數內部的一個不起作用

+0

'#this函數調用它自己,所以它的遞歸':) – Ben 2012-07-25 08:55:52

+0

在你做foreach之前(這是失敗),你可以做'print_r($ result2); – BenOfTheNorth 2012-07-25 10:04:50

+0

Array([id] => 2 [parent_id] => 1 [title] =();這將顯示數組中的實際內容並在該點後終止腳本(更易於在此處進行調試) > sub header 1) 顯示當我輸入您的代碼只是上面的foreach() – Pidge 2012-07-25 10:08:26

回答

0

謝謝所有幫助,但JEY設法基本上給了我全新的代碼笑

這裏解決我的問題是另外一個問題鏈接到他的代碼: Categories with sub PHP/MYSQL

謝謝你和其他人! :)

0

函數調用失敗的原因是因爲您沒有將代碼包裝在PHP標記中,而是您已經用JS標籤包裝了它們。

+0

有點derp由我那裏。更新的問題:) – Pidge 2012-07-25 09:53:55

0

替換<?php<script...線,並與?>

</script>行,你有服務器端代碼在PHP中,沒有客戶端的JavaScript(由語法判斷)

+0

有點derp由我那裏。更新的問題:) – Pidge 2012-07-25 09:54:06