Jump to content

Function to call itself: nested php comments


Ozii

Recommended Posts

Hi, first post here.  I'm wanting to create a php script which will call itself in a recursive function so that nested comments are made ..

An example of a perfect hierarchy would be as bellow...

  • Comment #1
  • -- Comment reply
  • --- Comment reply
  • --- Comment reply
  • ------ Comment reply
  • -------- Comment reply
  • ---------- Comment reply
  • --- Comment reply
  • --- Comment reply
  • Comment #2
  • -- Comment reply
  • ------ Comment reply
  • -- Comment reply

Note how they go deep into the comment replies (should support 7-25 comments in comments/deep) At the moment it only goes three deep as the recursive function doesn't  work...

I have created the function, but for some reason the line "comment($row['id']);" in the recursive function isn't preforming anything, commented or un commented. However looks fine to me.

function comment($reply_to_id){

global $db;

echo $reply_to_id;

$stmt11 = $db->prepare('SELECT * FROM `posts` WHERE reply_to = :thing');

$stmt11->execute(['thing' => $reply_to_id]);

while ($row = $stmt11->fetch()) {

echo "<br>";

echo " //----------[UID: ".$row['post_by']."]----------".$row['date']."----------->>> ";

echo $row['content'];

// comment($row['id']);

}

}

The full code is ..

<?php require('includes/config.php');

//define page title

$title = 'Thread Page';

//include header template

require('layout/header.php');

echo "<h1>the Forum // make post </h1>";

$id = $_GET['id'];

$reply = $_GET['reply'];

$rando1;

$test = $_GET['test'];

$index = 1;

?>

<?php

function indent(){

echo "-";

}

function stars($index){

//example to demonstrate star pattern-2

for($i=1; $i<=$index; $i++) {

for($j=1; $j<=$i; $j++)

{

echo '*';

}

echo '*';

}

}

function comment($reply_to_id){

global $db;

echo $reply_to_id;

$stmt11 = $db->prepare('SELECT * FROM `posts` WHERE reply_to = :thing');

$stmt11->execute(['thing' => $reply_to_id]);

while ($row = $stmt11->fetch()) {

echo "<br>";

echo " //----------[UID: ".$row['post_by']."]----------".$row['date']."----------->>> ";

echo $row['content'];

// comment($row['id']);



}



}



?>

<ul>

<?php

$rando_id = null;

// dealing with inital thread

$stmt = $db->prepare('SELECT * FROM `topics` WHERE rando_id = :topic_id');

$stmt->execute(['topic_id' => $id]);

while ($row = $stmt->fetch())

{

echo "Contents:<br>";

echo $row['contents'];

echo "<br><br>By: ";

$stmt2 = $db->prepare('SELECT * FROM `members` WHERE memberID = :mem_id');

$stmt2->execute(['mem_id' => $row['topic_by']]);

while ($row2 = $stmt2->fetch())

{

echo "<a href='profile.php?id=".$row2['user_ID']."'>".$row2['username']."</a><br>";



comment($row2['reply_id']);

}

echo "Timestamp: ".$row['date']."<br>";

echo "<a href='post_post.php?type='>Post reply</a><br>";

echo "----------------------";

echo "<br>";





}

echo "<br>";

$stmt3 = $db->prepare('SELECT * FROM `posts` WHERE reply_to = :reply_to');

$stmt3->execute(['reply_to' => $id]);

while ($row3 = $stmt3->fetch())

{

echo "<br>";

echo "// UID: [".$row3['post_by']."] ---- ".$row3['date']."------->> ".$row3['content']." <a href='post_post.php'>Reply</a>";

// comment($row3['reply_id']);




$reply_to_id = $row3['reply_id'];

$stmt11 = $db->prepare('SELECT * FROM `posts` WHERE reply_to = :thing');

$stmt11->execute(['thing' => $reply_to_id]);

while ($row = $stmt11->fetch())

{



// ----------------------------- SEE HERE (sp[lice]) -----------------------------



echo "<br>---[UID:";

echo $row['post_by']."] -- ".$row['date'].": ";

echo $row['content'];

echo " <a href='reply.php'>Reply</a>";

echo " [Reply to: ".$row['reply_to']."]";

echo " [Reply ID: ".$row['reply_id']."]";

$reply_to_id=$row['reply_id'];

$stmt111 = $db->prepare('SELECT * FROM `posts` WHERE reply_to = :thing');

$stmt111->execute(['thing' => $reply_to_id]);

while ($row33 = $stmt111->fetch()) {

echo "<br>--------[UID:";

echo $row33['post_by']."] -------- ".$row['date'].": ";

echo $row33['content'];

echo " <a href='reply.php'>Reply</a>";

echo " [Reply to: ".$row33['reply_to']."]";

echo " [Reply ID: ".$row33['reply_id']."]";

echo "<br>";

comment($row33['reply_id']);







}} // ------------------------------------------------------

}

?>

</ul>

<?php

if ($user->is_logged_in()){

} else {

echo "<h2>Login to create post </h2>";

echo "<a href='login.php'>Click to login</a>";

}

?>

<?php

//include header template

require('layout/footer.php');

?>

 

Link to comment
Share on other sites

  • Don't use "SELECT * ". Specify the columns you want. This makes it easier for others, like me, to understand what is in the table and what the query is doing.
  • Indent your code to show the nested structure of loops etc.

If you had done those I might have given this problem more than a cursory glance. So you'll have to settle for a generic example of using a recursive function to give an indented list of parent/child elements.

Also,

  • Don't run queries inside loops. Use JOINs to get all the data in a single query

THE DATA

TABLE: category
+----+---------+--------+
| id | name    | parent |
+----+---------+--------+
| 1  | happy   | 0      |
| 2  | comet   | 0      |
| 3  | grumpy  | 0      |
| 4  | prancer | 1      |
| 5  | bashful | 1      |
| 6  | dancer  | 2      |
| 7  | doc     | 2      |
| 8  | blitzen | 2      |
| 9  | dasher  | 3      |
| 10 | donner  | 1      |
| 11 | vixen   | 1      |
| 12 | cupid   | 8      |
+----+---------+--------+

THE OUTPUT

 

image.png.b2791999778076ea5546a24a149f0ff6.png

THE CODE

<?php
$sql = "SELECT id, name, parent
        FROM category";
$res = $db->query($sql);
//
// store arrays of items for each parent in an array
//
while (list($id, $name, $parent) = $res->fetch(PDO::FETCH_NUM)) {
    $data[$parent][] = array('id'=>$id, 'name'=>$name);
}


/**
* recursive function to print a category then its child categories
*  
* @param array $arr    category data
* @param int $parent   parent category
* @param int $level    hierarchy level
*/
    function displayHierarchy(&$arr, $parent, $level=0)
    {
        if (isset($arr[$parent])) {
            echo "<ul>\n";
            foreach($arr[$parent] as $rec)
            {
                echo "<li class='li$level'>{$rec['name']}\n";
                if (isset($arr[$rec['id']]))
                	displayHierarchy($arr, $rec['id'], $level+1);
                echo "</li>\n";
            }
            echo "</ul>\n";
        }
    }
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
<style type="text/css">
    body { font-family: verdana,sans-serif; font-size: 11pt; padding: 50px; }
    li   { font-weight: 600;}
    .li0 { color: red; }
    .li1 { color: green; }
    .li2 { color: blue; }

</style>
</head>
<body>
     <?php
         displayHierarchy($data, 0);
     ?>
</body>
</html>

 

  • Like 1
  • Great Answer 2
Link to comment
Share on other sites

30 minutes ago, Ozii said:

Could you provide the SQL dump for that database?

Here you go...

CREATE TABLE `category` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `parent` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `category`
--

INSERT INTO `category` VALUES 
(1,'happy',0),
(2,'comet',1),
(3,'grumpy',0),
(4,'prancer',3),
(5,'bashful',0),
(6,'dancer',3),
(7,'doc',0),
(8,'blitzen',10),
(9,'dasher',7),
(10,'donner',5),
(11,'vixen',1),
(12,'cupid',2),
(13,'rudolph',3);

-- Dump completed on 2021-06-15 15:43:51

Make sure you you have error reporting turned on in your php.ini file. Also turn display_errors and display_startup_errors on.

  • Great Answer 1
Link to comment
Share on other sites

  • 1 year later...


How would I make the connection to the database for this code snippet ? Does it use PDO?  Also, how would it look with this query ? Would this work? 

If it doesn't use PDO, could you show me it with PDO?
 

Quote

SELECT comment_id, parent, news_id, user_id, content, karma, removed, date, last_update, aproved, anonymous, image_upld FROM comment WHERE news_id = ? AND parent = '0' ORDER BY comment_id DESC

On 6/15/2021 at 1:27 PM, Barand said:
<?php
$sql = "SELECT id, name, parent
        FROM category";
$res = $db->query($sql);
//
// store arrays of items for each parent in an array
//
while (list($id, $name, $parent) = $res->fetch(PDO::FETCH_NUM)) {
    $data[$parent][] = array('id'=>$id, 'name'=>$name);
}


/**
* recursive function to print a category then its child categories
*  
* @param array $arr    category data
* @param int $parent   parent category
* @param int $level    hierarchy level
*/
    function displayHierarchy(&$arr, $parent, $level=0)
    {
        if (isset($arr[$parent])) {
            echo "<ul>\n";
            foreach($arr[$parent] as $rec)
            {
                echo "<li class='li$level'>{$rec['name']}\n";
                if (isset($arr[$rec['id']]))
                	displayHierarchy($arr, $rec['id'], $level+1);
                echo "</li>\n";
            }
            echo "</ul>\n";
        }
    }
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
<style type="text/css">
    body { font-family: verdana,sans-serif; font-size: 11pt; padding: 50px; }
    li   { font-weight: 600;}
    .li0 { color: red; }
    .li1 { color: green; }
    .li2 { color: blue; }

</style>
</head>
<body>
     <?php
         displayHierarchy($data, 0);
     ?>
</body>
</html>

 

 

Edited by oz11
Link to comment
Share on other sites

yes it is using the PDO extension. you can tell from the fetch mode being used, but this doesn't actually matter, because the database specific code is only querying for all the matching data, then indexing/pivoting it using the parent id value. that's not anything that's specific to the database extension. PDO just happens to have a fetch mode that will do this for you.

you do realize that this processing is exactly what i just posted in your other thread, just with different names?

Link to comment
Share on other sites

1 hour ago, mac_gyver said:

yes it is using the PDO extension. you can tell from the fetch mode being used, but this doesn't actually matter, because the database specific code is only querying for all the matching data, then indexing/pivoting it using the parent id value. that's not anything that's specific to the database extension. PDO just happens to have a fetch mode that will do this for you.

you do realize that this processing is exactly what i just posted in your other thread, just with different names?

Ah. that makes a lot of sense. I'll focus on the code you posted next. Thanks pal, huge help.:touche:

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.