Get Ancestors tree view against specific child id - php

I have a table for task with name tbl_tasks . This have data and also have parent_id.
Structure of table is
t_id, project_id, title , parent_id
1 1 Task1 0
data 2 1 Sub Task1 1
3 1 Child Sub task1 2
And there is another table with name tbl_sharedtasks in this table have data of shared task.
Structure of table is
project_id,user_id,t_id,createdby
data 1 1 3 3
When I want to show a Ancestors tree view for my shared task this detect only one record but not detect its parent record. which should 1 and 2 also because shared t_id 3 have pareint_id 2 and 2 have pareint_id 1
This is my code
$qry="SELECT sh.task_id,tsk.* FROM tbl_sharedtasks sh,tbl_tasks tsk where sh.project_id=1 and sh.user_id=1 and tsk.t_id=sh.task_id";
$result=mysql_query($qry);
$arrayCategories2 = array();
while($row = mysql_fetch_assoc($result)){
$arrayCategories2[$row['t_id']] = array("parent_id" => $row['parent_id'], "title" =>
$row['title'],"task_id" => $row['t_id']);
}
?>
<?php
if(mysql_num_rows($result)!=0)
{
?>
<?php
createTreeView($arrayCategories2, 0); ?>
<?php
}?>
This is my CreateTreeView Funciton
function createTreeView($array, $currentParent, $currLevel = 0, $prevLevel = -1)
{
$id=0;
foreach ($array as $categoryId => $category)
{
$id++;
if ($currentParent == $category['parent_id'])
{
if ($currLevel > $prevLevel) echo " <ul style='list-style:none; cursor:pointer' id='folder21'> ";
if ($currLevel == $prevLevel) echo " </li> ";
echo "<li > <span class='file'> ";?><a onClick="selecttaskval('<?php echo $category['task_id'];?>','<?php echo $category['title'];?>');"><?php echo $category['title'];?></a> </span>
<?php
if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }
$currLevel++;
createTreeView ($array, $categoryId, $currLevel, $prevLevel);
$currLevel--;
}
}
if ($currLevel == $prevLevel) echo " </li> </ul> ";
}
This is working fine only when I select records from tbl_tasks but not when I want to detect it from my shared table.
Please help with thanks

Related

drop down menu from database

I am want to make a navigation menu with a sub menu on hover. I want to get this data from my database (to make it dynamic if data in database changes menu bar changes). In my database I have a table with the the following fields:
ID, Name, Level, Parent_id. Level can be 0 or 1. 0 for main menu 1 for sub menu the id of a main menu is tied to the parent_id field.
So for instance:
ID Name Level Parent_id
1 Test 0
2 Test2 0
3 Test_sub 1 1
4 Test_sub2 2 2
I have managed to get the main menu items from the db but now I am a little bit stuck. This is my code any help would be appriciated.
<?php
$q2= "SELECT * from menu where level = 0 ";
$q2result = $db->query($q2);
while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
echo "
<ul>
<li><a href='#' ><span> " . $a2['name'] . " </span></a>
<ul>
<li><a href='#' ><span> test </span></a></li>
</ul>
</ul>
";
}
?>
First load all your datas into variables. Never print/echo while in SQL statement.
<?php
$q2= "SELECT * FROM menu ORDER BY Level ASC";
$q2result = $db->query($q2);
$nodes=array();
while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
// assuming one parent node has already been assigned, due do level order into the SQL
if($node['Level']>0 && isset($nodes[$a2['id']])) {
$nodes[$a2['id']]['nodes'][]=$a2;
} else {
// parent node
$nodes[$a2['id']]=$a2;
$nodes[$a2['id']]['nodes']=array();
}
}
print "<ul>";
foreach($nodes as $node) {
print "<li>";
print "<a href='#'>".$node['Name']."</a>";
if(sizeof($node['nodes'])>0) {
print "<ul>";
foreach($node['nodes'] as $subnode) {
print "<li><a href='#'>".$subnode['Name']."</a></li>";
}
print "</ul>";
}
print "</li>";
}
print "</ul>";
?>
This may be much more improved, but with this, you can do what you ask, and improve it.

recursive php category tree extended

I have been searching all over the forum but could not locate the answer to my specific question. I hope you can help me, for it has taken me A LOT of time to figure this out as a beginning PHP programmer.
I have a page that listens to this URL : .../.../edit_cat.php?id=24
I want to have a nice category tree. I have accomplished this, but I want all categories with no children to be a link to page post.php and all parent that do have children to be a link but only to show the other categories. Some sort of dropdown menu you might call it. So no children is post.php and if has children then drop the rest of children down. I hope this makes it clear...This is whay I have so far. It works as a tree but not how I wish it to be:
<h2>This is the current category tree</h2>
<?php
category_tree(0);
function category_tree($catid){
include '../config/connect.php';
$result = $db->prepare("SELECT * FROM categories WHERE parent_id = '".$catid."'");
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
$i = 0;
if ($i == 0){ echo '<ul class="cattree">';}
echo '<li>' . $row['cat_title'] . '';
category_tree($row['cat_id']);
echo '</li>';
$i++;
if ($i > 0){ echo '</ul>'; }
endwhile;
}
?>
My table of categories looks like this:
cat_id | cat_title | parent_id
1 some_title 0
2 some_title 1
3 title! 2
4 main_title 0
5 titellos! 4
Here is something I did last year, a query returns each line, with the idx, parent_idx and label of the line.
First call:
print_list(1, 0, $lines);
Function:
function print_list($parent, $level, $ar) {
$children = filter_by_parent($parent, $ar);
if (empty($children)) {
return;
}
echo '<ul>';
foreach ($children as $child) {
include PATH_PUBLIC . 'clients/simili/line.php';
print_list($child['Child_Idx'], ($level + 1), $ar);
echo '</li>';
}
echo '</ul>';
}
Second function:
function filter_by_parent($parent_id, $ar){
$retval = array();
foreach($ar as $a) {
if ($a['Parent_Idx'] == $parent_id) {
$retval[] = $a;
}
}
return $retval;
}
And the html called in the function:
<li class="no" data-id="<?php echo $child['Child_Idx']; ?>" data-parent-id="<?php echo $child['Parent_Idx']; ?>">
<i class="fa fa-plus-square-o"></i>
<i class="fa fa-minus-square-o"></i>
<span class="name">
<label><?php echo $child['Child_Name']; ?></label>
<i class="fa fa-book" title="Détails de l'Unité d'Organisation"></i>
</span>
<div class="chiffres">
<span class="inscrits"><?php echo $child['Nb_Collab']; ?></span>
<span class="etp-collab"><?php echo $child['ETP_Collab']; ?></span>
<span class="etp-postes"><?php echo $child['ETP_Postes']; ?></span>
<span class="etp-unit"><?php echo $child['ETP_Unit']; ?></span>
</div>
Ok, I don't know anything about PHP, but here's how you can add a "HasChildren" column to your sql query:
SELECT c.*,
CASE
WHEN EXISTS(SELECT * FROM Categories c1 WHERE c1.parent_id=c.cat_id) THEN 1
ELSE 0
END AS HasChildren
FROM Categories c
WHERE ParentID = #CatID

Dynamic Drop Down Menu and submenu php mysql

I have a menu that needs to be created dynamically from the database.
need to have menu and submenu
for example (wht i want):
<ul class="dropdown">
<li>Link 1 </li>
<li>Link 2 </li>
<li>Link 3 </li>
<li>Link 4
<ul class="sub_menu">
<li>Link 4 - 1</li>
<li>Link 4 - 2</li>
<li>Link 4 - 3</li>
</ul>
</li>
<li>Link 5</li>
<li>Link 6 </li>
</ul>
below is the code i used for menu using function i want submenu as well
function listMenu(){
$ans = $this->select("cat_id,cat_name","s_category","1");
if(is_array($ans)){
foreach($ans as $val){
echo
"<li><a href=\"post-summary.php?cid=$val[0]\" >$val[1]</a></li>";
}
}
else{
echo "";
}
}
database is as follows:-
CREATE TABLE IF NOT EXISTS `s_category` (
`cat_id` int(11) NOT NULL AUTO_INCREMENT,
`cat_name` varchar(15) NOT NULL,
`cat_uid` int(2) NOT NULL,
`cat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`cat_parent` int(11) DEFAULT '0',
`cat_sort` int(11) DEFAULT NULL,
`cat_delete` int(1) DEFAULT '0',
PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
You need to have a column, let we name it parentId in the s_category table.
Example values in there:
catId,catName,parentId
1,Vehicles,null
2,Planes,null
3,Cars,1
4,Bicycles,1
So your structure will be like:
- Vehicles
- Cars
- Bicycles
- Planes
You'll need to get the data like this (to be considered as pseudocode):
$topLevelItems = (select catId, catName from s_category where parentId is null)
foreach($topLevelItems as $item) {
echo '$item["catName"]';
$subItems = (select catId, catName from s_category where parentId=$item['catId'])
foreach($subItems as $subItem) {
echo '$subItem["catName"]';
}
}
You need to re-write the SQL part to match your case. This will work if you have just one inner level, e.g. no sub-sub-menus. If you plan to use sub-sub-menus you'll need recursive function.
as far as menus are concerned storing the submenus as a comma seperated values in the database would come handy.
ie consider a table with id,menus,submenus(several submenus seperated by a comma).
function listMenu(){
$ans = $this->select("menus,submenus");
if(is_array($ans)){
foreach($ans as $val){
echo "<li><a href=\"post-summary.php?cid=$val[0]\" >$val[0]</a>"; //menus
$submenu = explode(",",$val[1]);
foreach($submenu as $values){
echo "<li><a href=\"post-summary.php?cid=$val[0]&proname=$values\" >$values</a></li>"; // submenus
}
echo "</li>";
}
}
}
try this
$con = db_connect();
$str = "select menus,submenus from your_tabel ";
$result = mysql_query($str,$con);
while($arr = mysql_fetch_array($result))
{
echo "<li><a href=\"post-summary.php?cid=$arr[0]\" >$arr [0]</a>"; //menus
$submenu = explode(",",$arr [1]);
//make sure you have several sub-menus else use a if condition here to avoid foreach error
foreach($submenu as $values){
echo "<li><a href=\"post-summary.php?cid=$arr[0]&proname=$values\" >$values</a></li>"; // submenus
}
echo "</li>";
}
this works fine for me just tested now
comment if working.
comment if not-working.
created your database and write function with code and change parameters
function getAllFrom($field, $table,$where = NULL, $and = NULL , $orderfield, $ordering = "DESC") {
global $con;
$getAll = $con->prepare("SELECT $field FROM $table where $where $and ORDER BY $orderfield $ordering");
$getAll->execute();
$all = $getAll->fetchAll();
return $all;}
<ul>
<?php
$allCats = getAllFrom("*", "categories", "parent = 0", "" , "cat_id", "ASC");
foreach ($allCats as $cat) { ?>
<li>
<?php
echo '<a href="categoreis.php?pagename=' . str_replace(' ', '-', $cat['name_cat']) . '&pageid=' . $cat["cat_id"] . '">
' . $cat['name_cat'] . '
</a>';
?>
<ul class="sub-menu[enter image description here][1]">
<?php
$catsub = $cat['cat_id'];
$SubCats = getAllFrom("*", "categories", "parent = {$catsub}", "" , "cat_id", "ASC");
foreach ($SubCats as $sub) { ?>
<li>
<?php
echo '<a href="categoreis.php?pagename=' . $sub['name_cat'] . '&pageid=' . $sub["cat_id"] . '">
' . $sub['name_cat'] . '
</a>';
?>
</li>
<?php }
?>
</ul>
</li>
<?php }
?>
</ul>

Getting sub categories from mysql for the main category

I am having some problem in retrieving sub categories from mysql database.I want to display the sub-categeories for the parent categories.I am able to get only the last sub category of a main category. The first sub-categories are not displaying **. In my table **i have category_id and category_parent_id.where category_parent_id will be '0' for parent category. .Thanks in advance
<ul class="betterList">
<?php
$con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
mysql_select_db("DB",$con);
$result=mysql_query("select * from table ")or die("No table available with this name"."<br/><br/>".mysql_error());
while($row=mysql_fetch_array($result))
{
$parent_id=$row['category_parent_id'];
$category_id=$row['category_id'];
if($parent_id==0)
{
?>
<li>
<?php echo $row['category_id'].$row['name_en-GB'];
$result1=mysql_query("select * from table where category_parent_id=".$category_id)or die("No data available with this name"."<br/><br/>".mysql_error());
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++)
{
while($row1=mysql_fetch_array($result1))
{
?>
<ul style="margin:0px;padding:0;">
<li><?php echo $row1['name_en-GB']?></li>
</ul>
<?php
}
}
}
?>
</li>
<?php } ?>
<?php }?>
</ul>
when i remove <li> tag which is at the end and keep it after at the end of in while i could display all the sub-catgeories but the css is not applying for that. Some thing is going wrong there but i couldn't figuer it out
Remove below and try again:
for($i=0;$i<$num_row;$i++)
{
Wow ! o_O
You're using old mysql_* functions ...
You wrote :
for($i=0;$i<$num_row;$i++)
And After :
while($row1=mysql_fetch_array($result1))
Both of these instructions are looping on each rows you got with this query.
Remove all of that:
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++) {
Cause this is useless.
The only important thing to loop on your results is
while($row1=mysql_fetch_array($result1))
You can also replace mysql_fetch_array() by mysql_fetch_assoc() that is lighter.
Your code will be optimizable but this should solve your problem.
Instead of doing nested loops, get everything with a join:
SELECT t1.category_id parent, t1.`name_en-GB` parent_name,
t2.category_id child, t2.`name_en-GB` child_name
FROM table t1
JOIN table t2 ON t2.parent_category_id = t1.category_id
WHERE t1.parent_category_id = 0
Then your loop would be:
$last_parent = null;
$first_cat = true;
while ($row = mysql_fetch_assoc($result)) {
if ($row['parent'] != $last_parent) {
$last_parent = $row['parent'];
if (!$first_cat) { // Close out the last UL and LI
echo '</ul></li>';
} else {
$first_cat = false;
}
echo '<li>' . $row['parent'] . $row['parent_name'];
echo '<ul style="margin:0px;padding:0;">';
}
echo '<li>' . $row['child_name'] . </li>
}
if (!$first_cat) {
echo '</ul></li>';
}
You had too many nested loops in your code: you had both a for and while loop that were both trying to loop over the rows of the inner query. Also, you were putting each child into its own <ul>, which is probably not what you wanted.
Just try whether this solutions work for u, if it works adjust your code accordingly
$result = mysql_query("select * from table WHERE category_parent_id = 0 ");
while($row=mysql_fetch_array($result)) {
$parent_id = $row['category_parent_id'];
$query = mysql_query("select * from table where category_parent_id = {$parent_id}");
while($sub_cats=mysql_fetch_array($query)) {
echo '<pre>'.print_r($sub_cats).'</pre>';
}
}
just by adding internal <ul> before while loop i could get subcategories.
<?php
echo "<ul>";
while($row1=mysql_fetch_array($result1))
{
?>
<li><?php echo $row1['name_en-GB']?></li>
<?php
}
echo " </ul>";

Multilevel menu from database records

I need some help with PHP. I have a multilevel css menu that works fine, but now I want to generate according to the records from a database.
The menu Code:
<div id="page-wrap">
<ul class="dropdown">
<li>Link 1 </li>
<li>Link 2 </li>
<li>Link 3 </li>
<li>Link 4
<ul class="sub_menu">
<li>Link 4 - 1</li>
<li>Link 4 - 2</li>
<li>Link 4 - 3</li>
</ul>
</li>
<li>Link 5</li>
<li>Link 6 </li>
</ul>
</div>
In the database every record has a field called main_manu which makes it a main link if the value of this field is Yes, and if the value is No then it has another field (sub_menu) which says the parent menu in which this link should be placed.! See the screenshot.
DB Fields
SO, now I don't know how to do the php piece that will get the records and if the value of the main_menu is yes, it will create a top level menu, and if the value of main_menu is no, it will create a sub level menu according to the value of sub_menu field.
Thanks a lot
UPDATE
This is the code I have so far and it works. It would be nice if I could use a single query instead of multiple nested queries.
<div id='page-wrap'>
<ul class='dropdown'>
<?
$sql_menu = "SELECT * FROM content WHERE visible = '1' and main_menu='yes' ";
$result_menu = mysql_query($sql_menu);
while($row = mysql_fetch_assoc($result_menu))
{
$id=$row['id'];
$menu_top=$row['menu_name'];
$menu_url=$row['menu_url'];
print "<li><a href='$menu_url'>$menu_top</a>";
$sql_sub = "SELECT * FROM content WHERE sub_menu = '$menu_url' ";
$result_sub = mysql_query($sql_sub);
$num_rows = mysql_num_rows($result_sub);
while($row = mysql_fetch_assoc($result_sub))
{
$id=$row['id'];
$menu_sub=$row['menu_name'];
$sub_url=$row['menu_url'];
If ($num_rows != 0)
{
print "<ul class='sub_menu'>
<li><a href='$sub_url'>$menu_sub</a></li>
</ul>";
}
}
print "</li>";
}
?>
</ul>
</div>
The code for this would be something like the following (This will need to be changed for whatever way you interact with the database etc.):
// Here we do a query to get all the rows from the table
$db_result = db_execute_query('SELECT * FROM `menu_table` ORDER BY `order_no`');
// Here we take the rows and put it into a structured array
$items = array();
$hierarchy = array('' => array());
while ($row = db_fetch_row($db_result)) {
$items[$row['menu_name']] = $row['menu_name_en'];
if ($row['main_menu'] == 'yes') {
$hierarchy[''][] = $row['menu_name'];
} else {
if (!isset($hierarchy[$row['sub_menu']]) {
$hierarchy[$row['sub_menu']] = array();
}
$hierarchy[$row['sub_menu']][] = $row['menu_name'];
}
}
// Here we define a recursive function to run through our $hierarchy array;
function show_menu($name = '') {
if (isset($hierarchy[$name])) {
if ($name == '') {
echo '<ul class="dropdown">';
} else {
echo '<ul class="sub_menu">';
}
foreach ($hierarchy[$name] as $sub) {
echo '<li>' . $items[$sub] . '';
show_menu($sub);
echo '</li>';
}
echo '</ul>';
}
}
// Here we execute the recursive function on the main menu
show_menu('');
Try to understand what I'm doing here instead of just implementing it verbatim. Once you get to know recursive functions, a whole new world can open for you.
Also note that your db table could be changed to make this code simpler
I think these link will help you out. if not please let me know i will give you the code
http://board.phpbuilder.com/showthread.php?10337808-how-to-create-menu-submenu-subsubmenu-using-php-mysql
http://www.sitepoint.com/forums/showthread.php?718237-how-to-create-dynamic-menu-and-submenu-using-php-and-mysql

Categories