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
Related
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.
I have what is probably a ridiculously simple problem to solve in PHP, but my brain will not engage.
I have products divided into categories. I have performed a successful query which gives me an array containing the products joined to their respective categories. Now I want to display them by category, splitting each category up into its own div. I have the following code:
$current_category = 0;
do
{
if($current_category != $row['category_id']){
echo '<div class="block">
<div class="menu">
<h4>'.$row['category_name'].'</h4>
<ul>';
do
{
echo '<li><a>'.$row['product_name'].'</a></li>';
}
while ($row['category_id'] == $current_category);
$current_category++;
//close list and divs
echo '</ul>
</div>
</div>';
}
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
But this only outputs the first product in each category, rather than outputting them all then moving on to the next. What am I doing wrong?
You need to get the next row in the inner loop, not in the outer one:
do {
// no need to check we're in the right category - we always are
$current_category = $row['category_id'];
echo '<div class="block">
<div class="menu">
<h4>'.$row['category_name'].'</h4>
<ul>';
do {
echo '<li><a>'.$row['product_name'].'</a></li>';
// !!! get the next row here
$row = $stmt->fetch(PDO::FETCH_ASSOC);
}
while ($row['category_id'] == $current_category);
//close list and divs
echo '</ul>
</div>
</div>';
// !!! and don't get it again here
} while ($row);
You need to make sure that your SQL query sorts by category first
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
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>";
It might be confusing and a bit difficult. I have a $fcomm variable that holds values as an array. This variable $fcomm is then assigned to an 'echo div' into another foreach loop. What I need is to make $fcomm loop itself while it gets assigned and echoed with each <div>. Here's the code...Thank you for any comments.
PHP:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id = '".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
$fcomm[] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm;
}
}
$fcomm variable holds strings of comments from SQL. So when I add $fcomm[$i] or any loop variable to $fcomm it yields just single letters from comments - all I need is to make $fcomm print whole strings but different ones and the ones that correspond to proper each <div>. When I tried to place $fcomm in an inside loop - it prints strings but each string is the same...
You need to increase the index you're trying to retrieve from the fcomm array. Note the changes using $j variable.
if ($fr_check > 0 ) {
$j=0;
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm[$j];
$j++;
}
}
Without knowing your code or column names etc., you probably need to populate $fcomm based on the friend IDs, and then echo out the corresponding comment in the foreach loop.
Something like this:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id =
'".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
// populate $fcomm sub-array using the ID used to select
// them, i.e. $fcom[$i2]
$fcomm[ $fcom[$i2] ][] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "<div id='frslide'>...</div>";
// echo out the right $fcomm depending on the ID, $fr_ids
foreach ($fcomm[$fr_ids] as $comment) {
echo '<div>', $comment, '</div>';
}
}
}