PHP - Function To Call Itself: Nested Php Comments
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 replyNote 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'); ?>
Similar TutorialsHi I'm wondering how I can output nested comments. I have written a viewthread.php file that works nicely so far. From index.php it gets the IDOfThread and passes this to a $number then outputs all the comments assigned to the Thread ID However I'd like to be able to respond to each comment to create nested comments This is my viewthread.php so far <!DOCTYPE html> <html> <header> <link href="styles.css" rel="stylesheet" type="text/css" media="all"> <title>test Image Board</title> <div class="header"> <a href="index.php" class="logo">test forum online</a> <div class="header-right"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Education</a> <a href="#about">Tech</a> </div> </div> </header> <body> <!-- <a href="CreateThread.php"> <h1>Create Thread</h1> </a> --> <div class ='Thread-grid-container'> <?php include 'dbconnect.php'; $number = intval($_GET['id']) ; session_start(); $_SESSION['id'] = $number ; $query = mysqli_query($conn, "SELECT * FROM Threads where id=$number") or die (mysqli_error($conn)); //Output Grid layout for a Thread post while ($row = mysqli_fetch_array($query)) { //output picture from upload folder $imageURL = 'upload/'.rawurlencode($row["filename"]); echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; }?> <div class="comment-upload-box"> <form action="CommentUpload.php" method="post" enctype="multipart/form-data"> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name="CommentText" cols="100" rows="10" > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </div> <div class='divTableForComments'> <div class='divTableBody'> <?php include 'dbconnect.php'; //Output Comments onto page //Create a variable for the Comment boxes so when clicking reply a text area shows $ChildCommentBoxes = "<div class='child-comment-upload-box' style='margin-left: 48px'> <form action='ChildCommentUpload.php' method='post' enctype'multipart/form-data'> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name='ChildCommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form>"; $query = mysqli_query($conn, "SELECT * FROM Posts where IDOfThread=$number") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText = nl2br($row['CommentText']) ; $ParentComment = "" ; $replies = "" ; if (empty($row['ParentId'])) { $ParentComment .= " <div class='divTableRow'> <div class='divTableCell'>{$row['User']} <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <div class='upvotes'> ⬆</div> <div class='upvotes'> ⬇</div> <div> view comment </div> <div>report </div> <div>permalink</div> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> $ChildCommentBoxes </div> </div> </div> </div> </div> \n"; } echo "$ParentComment "; } ?> <div class ="sidebar"> </div> </body> </html> <script> var coll = document.getElementsByClassName("collapse"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> var coll2 = document.getElementsByClassName("CommentChildButton"); var i; for (i = 0; i < coll2.length; i++) { coll2[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block ") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> And this is what it looks like I think I would probably change the margin of the responses to jut them in a bit and am thinking the best way would be to create a function that cycles through and where it finds a ParentId of a comment matching the Posts.id it would then put this beneath it? My comments are stored in a table titled Posts and Posts looks like
MariaDB [test]> describe Posts ; +---------------+-----------------+------+-----+---------------------+-------------------------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-----------------+------+-----+---------------------+-------------------------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | User | varchar(30) | NO | | NULL | | | PostTimeStamp | timestamp | NO | | current_timestamp() | on update current_timestamp() | | CommentText | varchar(8000) | YES | | NULL | | | IDOfThread | int(11) | YES | | NULL | | | Upvotes | int(11) | NO | | 0 | | | ParentId | int(11) | YES | | NULL | | +---------------+-----------------+------+-----+---------------------+-------------------------------+ 7 rows in set (0.002 sec)
This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=319682.0 I can call the following function successfully as a single php program // Acknowledge and clear the orders function ack($client, $merchant, $id) { $docs = array('string' => $id); $params = array('merchant' => $merchant, 'documentIdentifierArray' => $docs); $result = $client->call('postDocumentDownloadAck', $params); return $result; } with $result = ack($t, $merchant,'2779540483'); successful output [documentDownloadAckProcessingStatus] => _SUCCESSFUL_ [documentID] => 2779540483 I'm trying to figure out how to call this function as an object from another program. Trying the following gives error ***Call to a member function call() on a non-object*** function postDocumentDownloadAck($t, $merchant, $id) { $this->error = null; $docs = array('string' => $this->id); $params = array('merchant' => $this->merchant, 'documentIdentifierArray' => $docs); ** I've tried the following which does nothing $result = $this->soap->call('postDocumentDownloadAck', $params); ** I've tried the following - which gives error "Call to a member function call() on a non-object" $result = $this->t->soap->call('postDocumentDownloadAck', $params); if($this->soap->fault) { $this->error = $result; return false; } return $result; } *** calling program snippet for above function $merchant= array( "merchant"=> $merchantid, "merchantName" => $merchantname, "email"=> $login, "password"=> $password); $t = new AmazonMerchantAPI($merchantid, $merchantname, $login, $password); $documentlist= $t->GetAllPendingDocumentInfo('_GET_ORDERS_DATA_'); $docid = $documentlist['MerchantDocumentInfo'][$i]['documentID']; $docs = array('string' => $docid); $ackorders = $t->postDocumentDownloadAck($t, $merchant,$docs); Any ideas of what I'm doing wrong are greatly appreciated. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=343263.0 Hi all, I have a function that is only used in the file it is declared in : /index.php Code: [Select] /** * This function is used to display form messages. * * @param string $msg This explains login and session status . * * @access private * * @return string */ function pred($msg) { return "<p class='content' style='color:red;'> $msg</p>"; } I'm using netbeans 7.0 (which by the way rocks !!!!! ), and I don't want to be able to see the documentation in other files when I start typing something similar. I read at pear.net coding standards that the '@param private' can be used on class methods. Is there a way to make the documentation private to the file that the function is declared in? I'm simply trying not to flood other files in the project with needless function suggestions. Thanks in advance. I have a problem with the "comments count" in the toggle link in my blog: www.albertosotophotography.com
I have this script for show/hide comments in main page:
<script type= "text/javascript"> // Show/Hide Comments jQuery(document).ready(function() { // Get #comments div var uniqueAppend = 1; var tempName = 'comments'; while(jQuery("#comments").length > 0 ){ jQuery("#comments").attr('id',tempName + uniqueAppend++).addClass('commentContainer') } var commentsDiv = jQuery('.commentContainer'); // Only do this work if that div isn't empty if (commentsDiv.length) { // Hide #comments div by default jQuery(commentsDiv).hide(); // Append a link to show/hide jQuery('<a/>') .attr('class', 'toggle-comments') .attr('href', '#') .html('Notes') .insertAfter(commentsDiv); // Encase button in .toggle-comments-container div jQuery('.toggle-comments').wrap(jQuery('<div/>', { class: 'toggle-comments-container' })) // When show/hide is clicked jQuery('.toggle-comments').on('click', function(e) { e.preventDefault(); // Show/hide the div using jQuery's toggle() var commentContainer = jQuery(this).parent('.toggle-comments-container').prev('.commentContainer'); jQuery(commentContainer).slideToggle('slow', function() { // change the text of the anchor var anchor = jQuery(commentContainer).siblings('.toggle-comments-container').children('.toggle-comments'); var anchorText = anchor.text() == 'Notes' ? 'Hide' : 'Notes'; jQuery(anchor).html(anchorText); }); }); } // End of commentsDiv.length }); // End of Show/Hide Comments </script>I use: .html('<?php comments_number( '0 notes', '1 note', '% notes' ); ?>')for name the "comments toggle link" with the count of comments for each single post. The problem is that all posts shows the same count: the comments presents in the first post. Someone can help me? Alberto Hi all, I want to call a javascript function from a php function like this: public function Buscar() { $HoraInicio = $_POST['edtHoraInicio']; $HoraFin = $_POST['edtHoraFin']; $FechaInicio = $_POST['edtFec1']; $FechaFin = $_POST['edtFec2']; $FechaMax = $FechaFin." ".$HoraFin.":00"; $FechaMin = $FechaInicio." ".$HoraInicio.":00"; $_GET["FechaMax"] = $FechaMax; $_GET["FechaMin"] = $FechaMin; echo $FechaMin; echo "<script language=javascript>alert('Hi.')</script>"; } but the function Buscar never show the alert but shows the $FechaMin I hopu u guys can help me out with this probem Thanks, Siddhartha Hi I have a table class and functions I want to call in another function but can't get it working. Some help will be very welcome. It seesm that the new table class is not working in this function if I pass the values to it, I have tested the class, it does get the post values I post to it so $_POST['id'] are being received as well as all the other $_POST's but the table class and find function is not working, it works fine if I don't put it in a function.. function edit() { if (isset($error)){ $error.="Please fix the error(s) above";} else { if ($_POST['id'] <> "") { $update =& new table($db, 'publisher'); $update->find($_POST['id']); $update->name = $_POST['name']; $update->url = $_POST['url']; $update->contact = $_POST['contact']; $update->address = $_POST['address']; $update->phone = $_POST['phone']; $update->email = $_POST['email']; $update->save(); $error = "The Publisher has been edited"; } } } HI...I hope u r all fine. I am using nested function ih php. this is not working.Here is the code. Code: [Select] <?php $array = array('a','b','c'); big_func($array); function big_func($arr) { function func1($arr) { foreach($arr as $list1){ echo $list1.'<br />'; } function func2($arr) { foreach($arr as $list2){ echo '<b>'.$list2.'</b><br />'; } } function func3(){ $arra = array('d','e','f'); func1($arra); } } } ?> This is not working.What is the problem with this code? please help me .....thanks........ I'm writing a program that allows users to input a stock and view a historical price chart. Code is straight out of libchart charting library. Problem is, user is supposed to enter the stock symbol from a form handler (index.php) which then passes the symbol as a variable to the charting function, which doesn't get called at all:
<? php
function index() { chart($_POST['userinput']};
} ?> .
<?php
function chart($stock)
{
$prices=getdata($stock); //returns array of prices from yahoo finance
$data=analyzer($prices); //produces metrics to be charted
graph($data); } ?> //plots the metrics, outputs .html
chart.php works on its own, as I've verified by hardcoding $argv='ibm'; in its code body. But index.php can't seem to call chart.php, as I've verified by including an echo/var_dump line in chart.php (doesn't get executed at all). It doesn't have anything to do with form handling either, as chart('ibm'); doesn't call chart.php either. I don't understand how a 6-line piece of code can be so problematic. All files are in the same folder, btw.
Thanks.
Hi
I'm trying to get the layout like i want but it's not easy
I have this file
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } if(isset($_POST['submitted'])) { $fgmembersite->PesquisarPorDatas(); } ?> <div id='fg_membersite_content'> <div class="CSSTableGenerator" > //I want the result here </div> <br>I want the result of this $fgmembersite->PesquisarPorDatas(); in "//I want the result here" the r of my code, when the user use the "Pesquisar" button this fucntion is called but the result comes out of my css any help please?? Edited by alphasil, 04 December 2014 - 10:32 AM. okay in modlogs.php i have a function Code: [Select] <?php function modmenu($page) { ?> <dl><dt class="<?php if ($page == 'modlogs') echo '';else echo 'ust'; ?> LEFT" style='margin-left:5px'><a href='mlogs.php'><b>User Logs</b></a> </dt><dt class="<?php if ($page == 'modlogs1') echo '';else echo 'ust'; ?> LEFT"><a href="modlogs1.php">Topic/Forum Actions</a></dt> <dd> <?php } ?> in modlogs1.php i try to echo Code: [Select] modmenu('modlogs1'); to show the menu but i get unidentified function? lol isn't functions global wtf? Is this even possible? I'm trying to call function nameGen from in the function nameGen but I just get an error saying cannot redeclare. I only want it to return $newName when it is not in the array $takenVals. can this only be done with another loop and a constant somewhere? Code: [Select] $newVarVals = array(); $takenVals = array(); $varCount = count($varArray); // contents are set else where and is fine for($i = 0 ; $i < $varCount; ++ $i) { function nameGen(&$varCount,&$takenVals){ $newName = rand(0,$varCount); if(in_array($newName,$takenVals)) { nameGen(&$varCount,&$takenVals); } else{ return $newName; } } $newName = nameGen(&$varCount,&$takenVals); $takenVals[] = $newName; $newNameToKeep = '$_'.$newName; $newVarVals[] = array('oldName' => $varArray[$i], 'newName' => $newNameToKeep); } error: Cannot redeclare nameGen() Hi im new to php Im excellent in C# more but lets not go into that I was wondering how to call this function. What am i doing wrong.. <?php if(isset($_POST['submit'])) { $startDate = strtotime($_POST['startdate']); $endDate = strtotime($_POST['enddate']); if($startDate != false && $endDate != false) { $startDate = date("y-m-d",$startDate); $endDate = date('y-m-d',$endDate); SearchForBookedRooms($startDate,$endDate); } else { echo "Please select both dates!"; } function SearchForBookedRooms($startDate,$endDate)//Calling this Function Here?? { } } ?> Been scratching my head about this all day. Cannot figure it out. Any help would be appreciated. Code: [Select] <?php $selectClause = 'SELECT * FROM idInfo WHERE'; $whereClause = ''; function addWhere($fxnName, $fxnValue) { if (!$whereClause) { return $fxnName . '=\'' . $fxnValue . '\''; } else { return ' AND ' . $fxnName . '=\'' . $fxnValue . '\''; } } $whereClause.=addWhere("firstName", $firstName); $whereClause.=addWhere("lastName", $lastName); $whereClause.=addWhere("idNum", $idNum); echo 'mysql_query("' . $selectClause . ' ' . $whereClause . '"); <br /><br />'; ?> This is meant to generate a query of the type: Code: [Select] SELECT * FROM idInfo WHERE firstName='firstNameINPUT' AND lastName='lastNameINPUT' AND idNum='idNumINPUT' For some reason, though, the if statement always reads false. No matter how I try to work the syntax Code: [Select] if (!$whereClause) if ($whereClause) if ($whereClause == NULL) if ($whereClause != NULL) if (empty($whereClause) etc. I've tried all of those and more, experimenting with and without quotes. They always return a FALSE for the existence of the variable, so that the string never contains the word "AND" as it should by the end. I've tried these same if statements outside the function and they work fine. Inside the function, it doesn't matter what the value of the variable is, the function runs as though it has no value. Comments? Suggestions? I am getting this error: Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\Work\Store\store.php on line 154 when I run the following code: Code: [Select] function categorySearch($sql) { $res = mysqli_query($this->conn,$sql); $this->results='<table>'; while($cRow = mysqli_fetch_array($res)) { function getCategoryName($cRow[0]) $this->results .= '<tr><td style="border: thin solid #000000;">' . $this->cat_str . '</td></tr>'; } $this->results.='</table>'; return $this->results; } Line 154 refers to this line: function getCategoryName($cRow[0]) Can anyone see what the problem is? This is the error that I am getting... Quote <br /> <b>Fatal error</b>: Call to undefined function readChatOnload() in <b>C:\server\xampp\htdocs\php\chat\readChat.php</b> on line <b>18</b><br /> And this is my php file... if(isset($_POST['function'])) { $function = $_POST['function']; switch($function) { case 'readNamesOnload': readNamesOnload(); break; case 'readNamesLoop': readNamesLoop(); break; case 'readChatOnload': readChatOnload(); break; case 'readChatLoop': readChatLoop(); break; } //READ NAMES ONLOAD function readNamesOnload() { die('readNamesOnload'); } //READ NAMES LOOP function readNamesLoop() { die('readNamesLoop'); } //READ CHAT ONLOAD function readChatOnload() { die('readChatOnload'); } //READ CHAT LOOP function readChatLoop() { die('readChatLoop'); } } I don't understand why this is happening. Thanks Code: [Select] <html> <center> <form method="post" action=""> <b>Email</b><br><input type="text" name="email"/><br> <b>Password</b><br><input type="password" name="password"/><br> <input type="submit" name="submit" value="Login"/><br> </form> <?php if(isset($_POST['submit'])){ echo echo_post($_POST['email']); function echo_post($postvar){ return $postvar; } } ?> </center> </html> the filename is index.php How come I get the undefined function echo_post on line 14? I know it is probably something simple but I am kind of new to this, if you could help me out that would be great I'd like to set my own error handler function to clear some session variables, but I do not want to completely replace php's internal error handler message reporting. Is there any way to mimic the internal error message reporting so I can define my own error handler function. function myErrorHandler(){ unset($_SESSION['var']); // HERE EXECUTE Normal PHP error message reporting } Thanks |