I'm having some issues getting a tree menu to work from bottom-up.
I already have a script to work from top-down, which works fine.
This is a very simplified version of my table:
+-----+-----------+--------------------+
| uid | parent_id | page_address |
+-----+-----------+--------------------+
| 1 | 0 | index.php |
| 2 | 0 | login.php |
| 3 | 2 | dashboard.php |
| 4 | 3 | bookings.php |
| 5 | 3 | documents.php |
| 6 | 4 | changebookings.php |
| 7 | 4 | activities.php |
+-----+-----------+--------------------+
The page_address field is unique.
I can work out what page the user is currently on, for example changebookings.php
I would then like a menu to look like this:
login.php
dashboard.php
bookings.php
changebookings.php
activities.php
documents.php
However, the closest I've got so far is the following tree:
login.php
bookings.php
changebookings.php
As you can see, my script currently only returns the actual parent, and not a list of links currently in the parent.
For those interested, the script I use in total is at the bottom of this post.
Is there any easier way to get the bottom-up tree as required?
Many thanks
Phil
EDIT:
I've finally got the code to work, for future users who stumble upon this post, I have added the functionality below:
$dataRows = $databaseQuery->fetchAll(); // Get all the tree menu records
$dataRows = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($dataRows as $row)
{
if($row['link_address']==substr($_SERVER['PHP_SELF'], 1, strlen($_SERVER['PHP_SELF'])-1))
{
$startingId = $row['parent_id'];
}
}
$menuTree = $this->constructChildTree($dataRows, $startingId);
private function constructChildTree(array $rows, $parentId, $nesting = 0)
{
$menu = array();
if(!in_array($nesting, $this->nestingData))
{
$this->nestingData[] = $nesting;
}
foreach($rows as $row)
{
if($row['parent_id']==$parentId && $parentId!=0)
{
$menu[] = $row['link_address'];
$newParentId = $this->getNextParent($rows, $row['parent_id']);
$parentChildren = $this->constructChildTree($rows, $newParentId, ($nesting+1));
if(count($parentChildren)>0)
{
foreach($parentChildren as $menuItem)
{
$menu[] = 'NESTING' . $nesting . '::' . $menuItem;
}
}
}
}
return $menu;
}
private function getNextParent($rows, $parentId)
{
foreach($rows as $row)
{
if($row['uid']==$parentId)
{
return $row['parent_id'];
}
}
}
Without reading your code you should be doing:
1) Get current page, look at parent ID.
2) Load all with that parent ID.
3) Get next Parent ID using current Parent ID as ID.
4) If new parent ID != 0, goto step 2 passing in the new Parent ID.
Sounds like you just need to edit your script to include ALL pages with the given ID as their parent ID.
<?PHP
$sql = "SELECT * FROM TABLE WHERE table parent_id=0";
$result = mysql_query($sql);
while($perant_menu = mysql_fetch_array($result))
{
echo display_child($perant_menu["uid"],$perant_menu["page_address"]);
}
// Recursive function
function display_child($parent_id,$name)
{
$sql= "SELECT * FROM table where parent_id = $parent_id";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
while($menu = mysql_fetch_array($result))
{
echo display_child($menu["id"],$menu["page_address"]);
}
}
else
{
echo $name;
}
}
?>
Related
I am a newbie to PHP and I am stuck at a certain point. I tried looking up a solution for it however, I didn't find exactly what I need.
My goal is to create a leaderboard, in which the values are displayed in descending order plus the rank and score are displayed. Furthermore, it should also display whether or not a tie is present.
The database should look like this:
+---------+------+----------------+-------+------+
| user_id | name | email | score | tied |
+---------+------+----------------+-------+------+
| 1 | SB | sb#gmail.com | 1 | 0 |
+---------+------+----------------+-------+------+
| 2 | AS | as#web.de | 2 | 0 |
+---------+------+----------------+-------+------+
| 3 | BR | br#yahoo.com | 5 | 1 |
+---------+------+----------------+-------+------+
| 4 | PJ | pj#gmail.com | 5 | 1 |
+---------+------+----------------+-------+------+
And the outputted table should look something like this:
+------+-------------+-------+------+
| rank | participant | score | tied |
+------+-------------+-------+------+
| 1 | BR | 5 | Yes |
+------+-------------+-------+------+
| 2 | PJ | 5 | Yes |
+------+-------------+-------+------+
| 3 | AS | 2 | No |
+------+-------------+-------+------+
| 4 | SB | 1 | No |
+------+-------------+-------+------+
I managed to display the rank, participant and the score in the right order. However, I can't bring the tied column to work in the way I want it to. It should change the value, whenever two rows (don't) have the same value.
The table is constructed by creating the <table> and the <thead> in usual html but the <tbody> is created by requiring a php file that creates the table content dynamically.
As one can see in the createTable code I tried to solve this problem by comparing the current row to the previous one. However, this approach only ended in me getting a syntax error. My thought on that would be that I cannot use a php variable in a SQL Query, moreover my knowledge doesn't exceed far enough to fix the problem myself. I didn't find a solution for that by researching as well.
My other concern with that approach would be that it doesn't check all values against all values. It only checks one to the previous one, so it doesn't compare the first one with the third one for example.
My question would be how I could accomplish the task with my approach or, if my approach was completely wrong, how I could come to a solution on another route.
index.php
<table class="table table-hover" id="test">
<thead>
<tr>
<th>Rank</th>
<th>Participant</th>
<th>Score</th>
<th>Tied</th>
</tr>
</thead>
<tbody>
<?php
require("./php/createTable.php");
?>
</tbody>
</table>
createTable.php
<?php
// Connection
$conn = new mysqli('localhost', 'root', '', 'ax');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
// Initalizing of variables
$count = 1;
$previous = '';
while($row = mysqli_fetch_array($result)) {
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
?>
<tr>
<td>
<?php
echo $count;
$count++;
?>
</td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['score'];?></td>
<td>
<?php
if ($row['tied'] == 0) {
echo 'No';
} else{
echo 'Yes';
}
?>
</td>
</tr>
<?php
}
?>
I think the problem is here
$index = $result['user_id'];
it should be
$index = $row['user_id'];
after updating tied you should retrieve it again from database
So I solved my question by myself, by coming up with a different approach.
First of all I deleted this part:
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
and the previous variable.
My new approach saves the whole table in a new array, gets the duplicate values with the array_count_values() method, proceeds to get the keys with the array_keys() method and updates the database via a SQL Query.
This is the code for the changed part:
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
$query = "SELECT * FROM names ORDER BY score DESC";
$sol = $conn->query("$query");
// initalizing of variables
$count = 1;
$data = array();
// inputs table into an array
while($rows = mysqli_fetch_array($sol)) {
$data[$rows['user_id']] = $rows['score'];
}
// -- Tied Column Sort --
// counts duplicates
$cnt_array = array_count_values($data);
// sets true (1) or false (0) in helper-array ($dup)
$dup = array();
foreach($cnt_array as $key=>$val){
if($val == 1){
$dup[$key] = 0;
}
else{
$dup[$key] = 1;
}
}
// gets keys of duplicates (array_keys()) and updates database accordingly ($update query)
foreach($dup as $key => $val){
if ($val == 1) {
$temp = array_keys($data, $key);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=1 WHERE user_id=$v";
$conn->query($update);
}
} else{
$temp = array_keys($data, $k);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=0 WHERE user_id=$v";
$conn->query($update);
}
}
}
Thank you all for answering and helping me get to the solution.
instead of the update code you've got use something simular
$query = "select score, count(*) as c from names group by score having c > 1";
then you will have the scores which have a tie, update the records with these scores and your done. Make sure to set tie to 0 at first for all rows and then run this solution
UPDATE for an even faster solution sql based:
First reset the database:
$update = "UPDATE names SET tied=0";
$conn->query($update);
All records have a tied = 0 value now. Next update all the records which have a tie
$update = "update docs set tied = 1 where score IN (
select score from docs
group by score having count(*) > 1)";
$conn->query($update);
All records with a tie now have tied = 1 as we select all scores which have two or more records and update all the records with those scores.
I have a table comments, thats look like this, added some mockup content as well:
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
| comment_id | user_id | movie_id | comment_parent_id | comment_content | comment_creation_datetime |
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
| 26 | 1 | 16329 | 0 | Första | 2016-01-24 10:42:49 |
| 27 | 1 | 16329 | 26 | Svar till första | 2016-01-24 10:42:55 |
| 28 | 1 | 16329 | 26 | Andra svar till förta | 2016-01-24 10:43:06 |
| 29 | 1 | 16329 | 28 | Svar till "andra svar till första" | 2016-01-24 10:43:23 |
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
Im trying to display the comments Reddit style, like this image:
Im trying to fetch all comments SELECT * FROM comments WHERE movie_id = :movie_id ORDER BY comment_creation_datetime DESC and then recursively echo them out.
I have tried a bunch of foreachloops, but none is working as expected
foreach($this->comments as $value){ ?>
<div class="comment">
Comment content <?php echo $value->comment_content; ?>
<?php if($value->comment_parent_id > 0){
foreach($value as $sub_comment){ ?>
<div class="comment">
comment comment on comment: <?php echo $value->comment_content; ?>
</div>
<?php }} ?>
</div>
<?php }
My question:
How do I echo out the comments in a nested Reddit style with foreach loop?
You need to both make a list of root comments, and hierarchically organize all of them. You can do both in one go:
$roots = [];
$all = [];
foreach($comments as $comment)
{
// Make sure all have a list of children
$comment->comments = [];
// Store all by ID in associative array
$all[$comment->comment_id] = $comment;
// Store the root comments in the roots array, and the others in their parent
if(empty($comment->comment_parent_id))
$roots[] = $comment;
else
$all[$comment->comment_parent_id]->comments[] = $comment;
}
// Check it's all done correctly!
print_r($roots);
You presorted the list by date, that's preserved in this approach. Also, as you only reorganized by reference this is lightning fast, and ready to be used in templating engines or anything - no need to print out inline like the other answers.
Working with the adjacency list model can be more problematic with SQL. You need to retrieves all the rows with a single query and store a reference of any parent's child in a lookup table.
$sth = $pdo->prepare("SELECT * FROM comments WHERE movie_id = ? ORDER BY comment_creation_datetime DESC");
$sth->execute([$movie_id]);
$comments = $sth->fetchAll(PDO::FETCH_ASSOC);
$lookup_table = [];
foreach ($comments as $comment_key => $comment) {
$lookup_table[$comment['comment_parent_id']][$comment_key] = $comment['comment_id'];
}
Now you can display them with
function recursive_child_display($comments, $lookup_table, $root = 0, $deep = 0)
{
if (isset($lookup_table[$root])) {
foreach ($lookup_table[$root] as $comment_key => $comment_id) {
// You can use $deep to test if you're in a comment of a comment
echo '<div class="comment">';
echo 'Comment content ', $comments[$comment_key]['comment_content'];
recursive_child_display($comments, $lookup_table, $comment_id, $deep+1);
echo '</div>';
}
}
}
Example:
// display all the comments from the root
recursive_child_display($comments, $lookup_table, 0);
// display all comments that are parent of comment_id 26
recursive_child_display($comments, $lookup_table, 26);
I would use some recursive function, you start with the ones with parent_id == 0 and recursively print all those who are their direct children.
This code is not tested, but you can get the idea:
function printComment($comment, $comments)
{
foreach($comments as $c)
{
if($c->parent_id == $comment->comment_id)
{
$output .= "<li>".printCommment($c)."</li>";
}
}
$output = "<ul>".$comment->comment_content."</ul>".$output;
return $output;
}
foreach($this->comments as $comment)
{
if($comment->parent_id == 0)
{
echo printComment($comment,$this->comments);
}
}
I have one table on my database that includes kategoriID,kategoriAd,kategoriEbeveyn.
It is like categoryID,catagoryName and categoryParent.
I want that happens that is when i try to delete main category, I can delete main category and sub categories.
-World
............ +Europe
....................... *Turkey
.................................**Istanbul
When I try to delete, This function works for World and Europe. But Turkey and Istanbul is still in my database. I couldn't delete those because of the error.
"mysql_fetch_array() expects parameter 1 to be resource, boolean given in"
| kategoriID | kategoriAd | kategoriEbeveyn |
| 1 | World | 0 |
| 2 | Europe | 1 |
| 3 | Turkey | 2 |
| 4 | Istanbul | 3 |
Here is my function.
<?php
function KategoriVeAltKategorileriSil(){
$kategoriID = $_GET['kategoriID'];
mysql_query("DELETE FROM kategoriler WHERE kategoriID = ' $kategoriID '") or die (mysql_error());
$delete = mysql_query("DELETE FROM kategoriler WHERE kategoriEbeveyn = ' $kategoriID ' ") or die (mysql_error());
if($delete){
while($silinecek = mysql_fetch_array($delete)){
KategoriVeAltKategorileriSil($silenecek[' kategoriID ']);
echo mysql_error();
}
echo "Kategori ve alt kategorileri silindi.";
}else{ echo "Silme işlemi gerçekleştirilemedi!" .mysql_error(); }
}
?>
Or Do i need to use Trigger?
function deleteCategory($kategoriID) {
$result=mysql_query("SELECT * FROM kategoriler WHERE kategoriEbeveyn='$kategoriID'");
if (mysql_num_rows($result)>0) {
while($row=mysql_fetch_array($result)) {
deleteCategory($row['kategoriID']);
}
}
mysql_query("DELETE FROM kategoriler WHERE kategoriID='$kategoriID'");
}
you can use this recursive function
The best way would be to make a request like :
DELETE FROM kategoriler WHERE ketegoriID IN (SELECT kategoriID
FROM kategoriler
WHERE kategoriID = ' $kategoriID ' or kategoriEbeveyn = ' $kategoriID ');
of course it's not complete because i don't know your databases structure
Well, the point is that you have a tree structure that is mapped to the flat (row) structure of the DB.
You will need to handle this with a recursive delete method.
Your code should probably look something like:
function DeleteCategory(catId)
{
GetChildCategoriesOf(catId)
if (num_rows > 0)
{
foreach(ChildCategoryFound)
{
DeleteCategory(ChildCatId); //Recursive call
}
}
Delete(catId) //Delete the parent as last action
}
My function looks like that. It works but does lots of work (recursively calls itself and does lots of db queries). There must be another way to do same thing but with array (with one query). I can't figure out how to modify this function to get it work with array.
function genMenu($parent, $level, $menu, $utype) {
global $db;
$stmt=$db->prepare("select id, name FROM navigation WHERE parent = ? AND menu=? AND user_type=?") or die($db->error);
$stmt->bind_param("iii", $parent, $menu, $utype) or die($stmt->error);
$stmt->execute() or die($stmt->error);
$stmt->store_result();
/* bind variables to prepared statement */
$stmt->bind_result($id, $name) or die($stmt->error);
if ($level > 0 && $stmt->num_rows > 0) {
echo "\n<ul>\n";
}
while ($stmt->fetch()) {
echo "<li>";
echo '' . $name . '';
//display this level's children
genMenu($id, $level+1, $menu, $utype);
echo "</li>\n\n";
}
if ($level > 0 && $stmt->num_rows > 0) {
echo "</ul>\n";
}
$stmt->close();
}
You can build a tree-based array fairly easily, so it'd be one single query and then a bunch of PHP logic to do the array building:
$tree = array();
$sql = "SELECT id, parent, name FROM menu WHERE parent ... etc.... ";
$results = mysql_query($sql) or die(mysql_error());
while(list($id, $parent, $name) = mysql_fetch_assoc($results)) {
$tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
if (!array_key_exists($tree[$parent]['children'][$id])) {
$tree[$parent]['children'][$id] = $id;
}
}
For this, I'm assuming that your tree has a top-level '0' node. if not, then you'll have to adjust things a bit.
This'd give you a double-linked tree structure. Each node in the tree has a list of its children in the ['children'] sub-array, and each node in the tree also points to its parent via the ['parent'] attribute.
Given a certain starting node, you can traverse back up the tree like this:
$cur_node = 57; // random number
$path = array();
do {
$parent = $tree[$cur_node]['parent'];
$path[] = $parent;
$cur_node = $parent;
} while ($parent != 0);
I think the first thing you can fix is removing the WHERE parent = ? clause and then work on the resulting query result, this will make you work a bit more in managing the result but will definitely safe you IO operations.
Using parts of Marc B Solution
$tree = array();
$sql = "select id, parent, name FROM navigation AND menu=? AND user_type=?";
$results = mysql_query($sql) or die(mysql_error());
while(list($id, $parent, $name) = mysql_fetch_assoc($results)) {
$tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
if (!array_key_exists($tree[$parent]['children'][$id])) {
$tree[$parent]['children'][$id] = $id;
}
}
print_r($tree);
Replace the ? with the actual values, and give that a run, what is your output?
Maybe not what you wanted, but it is great when it comes to trees.
You would have to rebuild your table and had some code to output the html, but you would have only one query. It could be worth the effort on the long run.
ie.If you have this menu
# Menu hierarchy:
- Home
- Product
|- Tv
|- Radio
- About us
It would looks like this in the db.
+----+----------+-----------+-----+-----+
| id | menu | parent_id | lft | rgt |
+----+----------+-----------+-----+-----+
| 1 | Home | null | 1 | 2 |
+----+----------+-----------+-----+-----+
| 2 | Product | null | 3 | 8 |
+----+----------+-----------+-----+-----+
| 3 | Tv | 2 | 4 | 5 |
+----+----------+-----------+-----+-----+
| 4 | Radio | 2 | 6 | 7 |
+----+----------+-----------+-----+-----+
| 5 | About us | null | 9 | 10 |
+----+----------+-----------+-----+-----+
The data could be fetch using a similar query
$select = "SELECT * FROM table_name WHERE lft BETWEEN 3 AND 8;"
To output a specific menu:
- Product
|- Tv
|- Radio
I know its not exactly the answer your were looking for, but FYI, there are other ways to use hierarchical tree data.
Good luck.
I wrote in the past an ugly way but with simple SELECT:
I store in text/varchar field strings like this:
/001
/001/001
/001/002
/002
/002/001
/002/001/001
Ignore the hebrew and look in window.aMessages array, to look how it works:
http://www.inn.co.il/Forum/Forum.aspx/t394009#4715854
I have been developing my own forum for about a week now and I am almost done with all of the code, however, I am stuck on one single issue that I have not been able to figure out.
Well, simply said I have sub forums that can be within any amount of other sub forums.
How would I create a path dynamically to any of those sub forums on the spot with PHP.
After the path is created I would use it within href's and other things.
I am guessing I would somehow need to traverse the database based on a ID column and another column that would link one sub forum to another sub forum.
Let's assume that my database table looks like this:
ID | Name | Link |
---+-------------+-------
1 | Forum-One | Top |
2 | Forum-Two | 1 |
3 | Forum-Three | 2 |
4 | Forum-Four | 2 |
5 | Forum-Five | 3 |
6 | Forum-Six | 3 |
How would I go about doing this - or is there something else that must be done instead?
I hope I was clear enough for everyone to understand.
EDIT:
include("inc/config.php");
function generateBreadcrumb($startingID){
$result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");
while($row = mysql_fetch_array($result))
{
$db_id=$row['ID'];
$db_name=$row['Name'];
}
if($db_id!='Top'){
return generateBreadCrumb($db_id);
} else {
return $db_name;
}
}
$startID='6';
echo generateBreadcrumb($startID);
First you need a terminating condition. So set your top level Forum[link] to null, or 'top', or something. Then its simply a matter of using a recursive function put your bread-crumb together.
So lets assume you wanted to go to display the breadcrumb to Forum-One:Forum-Three:Forum-Six , better known as Forum-Six.
Example code:
<?php
$yourForumId = 6; // replace this dynamically with your forum;
$breadcrumb = generateBreadcrumb($yourForum);
function generateBreadcrumb($startingForumId){
$sql= "SELECT Name ,link FROM Forums WHERE ID = ".$startingForumId;
//run your $sql however you do to get results
//assuming you get associative arrays back
if($res['link'] != 'top'){
return generateBreadCrumb($res['link']).":".$res['Name'];
} else {
return $res['Name'];
}
}
echo $breadcrumb;
?>
It's recursion, which if you're new to it may seem complicated, but I hope that helps!
EDIT: here's your code with the needed edit...
include("inc/config.php");
function generateBreadcrumb($startingID){
$result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");
$row = mysql_fetch_array($result);
$db_id=$row['link'];
$db_name=$row['Name'];
if($db_id!='Top'){
return generateBreadCrumb($db_id).":".$db_name;
} else {
return $db_name;
}
}
$startID='6';
echo generateBreadcrumb($startID);