【问题标题】:Treeview populated from database从数据库填充的树视图
【发布时间】:2012-07-25 08:53:46
【问题描述】:

我一直试图弄清楚如何使用我遇到的各种示例从数据库中创建一个树视图,但到目前为止还没有成功。

我的数据库结构如下:

id | parent_id | title | Urgency(紧急未落实)

最终结果应该生成一个树形视图,其中紧急程度的值决定了用于每个项目的图像。

我最近尝试使用的代码是:

<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>

基本上我的代码不起作用。我可以尝试解决什么问题?

编辑

我更改了一些代码以修复几个错误 所以现在我看到的是:

  • 1
  • 2
  • 5

警告:在第 13 行的 C:\Program Files\EasyPHP-5.3.9\www\test.php 中为 foreach() 提供的参数无效

重复 100 次直到中止。不知道为什么,因为代码中的foreach()都是一样的,但是函数里面的那个不行。

【问题讨论】:

  • #this function calls it self, so its recursive :)
  • 在执行 foreach 之前(失败),您能否执行 print_r($result2); exit(); - 这将向我们展示数组中的实际内容并在该点之后终止脚本(此时更易于调试)
  • Array ( [id] => 2 [parent_id] => 1 [title] => sub header 1 ) 当我在 foreach() 上方输入您的代码时显示
  • 看这个...它对你有帮助stackoverflow.com/questions/10215980/…
  • @jey 谢谢,您应该将其发布为答案,以便我接受! :)

标签: php mysql database treeview


【解决方案1】:

函数调用失败的原因是因为您没有将该代码包装在 PHP 标记中,而是将它们包装在 JS 标记中。

【讨论】:

    【解决方案2】:

    &lt;script... 行替换为&lt;?php,将&lt;/script&gt; 行替换为?&gt;

    您在 php 中有服务器端代码,而不是客户端 javascript(根据语法判断)

    【讨论】:

      【解决方案3】:

      感谢您提供的所有帮助,但 Jey 基本上通过给我全新的代码来解决我的问题,哈哈

      这是他关于另一个问题的代码的链接: Categories with sub PHP / MYSQL

      谢谢杰伊和其他所有人! :)

      【讨论】:

        猜你喜欢
        • 2013-08-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多