reisve Posted May 4, 2013 Share Posted May 4, 2013 HiI'm trying to adapt a function to Display Hierarchical Data I found on sitepointThe code I got so far is: <?php // $parent is the parent of the children we want to see // $level is increased when we go deeper into the tree, // used to display a nice indented tree $link = mysql_connect("localhost", "root", "palhaco"); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('testecat', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } function display_children($parent, $level) { // retrieve all children of $parent $result = mysql_query('SELECT title FROM testcat '. 'WHERE parent="'.$parent.'";'); // display each child while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { // indent and display the title of this child echo str_repeat(' ',$level).$row['title']."\n"; // call this function again to display this // child's children display_children($row['title'], $level+1); } } display_children('',0); ?> But the only thing I got is an error message:"Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\Web Data\testcat.php on line 20 "Can some one help me please? Link to comment https://forums.phpfreaks.com/topic/277623-display-hierarchical-data-mysql-error/ Share on other sites More sharing options...
Barand Posted May 4, 2013 Share Posted May 4, 2013 I use this version which doesn't continually query the database <?php include("testDBconnect.php"); $sql = "SELECT category_id, name, parent FROM category"; $res = mysql_query($sql); while (list($id, $name, $parent) = mysql_fetch_row($res)) { $data[$parent][] = array('id'=>$id, 'name'=>$name); } // call the recursive function displayHierarchy($data, 0); // function to print a category then its child categories function displayHierarchy(&$arr, $parent, $indent=0) { $ind = $indent * 50; if (isset($arr[$parent])) foreach($arr[$parent] as $rec) { echo "<div style='width:300px; margin-top:5px; margin-left: {$ind}px; padding:5px; border:1px solid gray;'> {$rec['name']} </div>" ; displayHierarchy($arr, $rec['id'], $indent+1); } } ?> Link to comment https://forums.phpfreaks.com/topic/277623-display-hierarchical-data-mysql-error/#findComment-1428182 Share on other sites More sharing options...
reisve Posted May 4, 2013 Author Share Posted May 4, 2013 It worked. Now I need to output the categories to a combobox that should be easy ThankYou Link to comment https://forums.phpfreaks.com/topic/277623-display-hierarchical-data-mysql-error/#findComment-1428217 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.