2012-07-25 174 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