PHP - Adding Comments
Hi all,
I've got a news table as such; `id` int(255) NOT NULL auto_increment, `title` mediumtext NOT NULL, `postedby` mediumtext NOT NULL, `text` mediumtext NOT NULL, `brief` mediumtext NOT NULL, `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, `image` varchar(255) NOT NULL default '', PRIMARY KEY (`id`) I was wondering in PHP how would i be able to add comments to the news? i.e Form: Name, IP (hidden), comments I'll add the name, ip and comments to the database But how do i go around adding that into php? Similar TutorialsI 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 Hello im trying to make a comment feature by having a link under my pictures kommentar.php?link=1 Then use the link=1 to see what comments that should be taken from the database. The comments have a linkid like this Linkid: Text: 1 a comment on first picture 1 another comment on first picture 2 a comment on second picture 2 another comment on second picture But i can't get my php to echo all the comments with the linkid of for example 1 without having to get them all separately. This is my script: <?php ob_start(); $host="localhost"; $username="****"; $password="******"; $db_name="db"; $tbl_name="comment"; mysql_connect($host, $username, $password)or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $linkid=filter_input(INPUT_GET,'link'); $sql="SELECT * FROM $tbl_name WHERE linkid='$linkid'"; $result=mysql_query($sql); $grejs=null; while(mysql_fetch_row($result)){ $grejs.="$row[0]"; } echo $grejs; ob_end_flush(); ?> Hello! I'm trying to dive into Dreamweaver's code so that I can better understand what the heck it's doing in order to modify it to my specific needs. My PHP book is great, but it just seems like Dreamweaver's code is much more complicated than how I'd write it based on what I've read about PHP (Disclaimer: been with PHP for a week). It would be incredibly helpful if someone could write comments for each of the lines in terms of what it's doing (the more specific the better). I appreciate that this is a bit of a tedious question to ask, but it would be really appreciated. Thank you. Code: [Select] $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form2")) { $insertSQL = sprintf("INSERT INTO users (first_name, last_name, user_type, email, school_id) VALUES (%s, %s, %s, %s, %s)", GetSQLValueString($_POST['first_name'], "text"), GetSQLValueString($_POST['last_name'], "text"), GetSQLValueString($_POST['user_type'], "text"), GetSQLValueString($_POST['email'], "text"), GetSQLValueString($_POST['school_id'], "int")); mysql_select_db($database_connalgebra, $connalgebra); $Result1 = mysql_query($insertSQL, $connalgebra) or die(mysql_error()); // The code below gives the last autogenerated userid. $id = mysql_insert_id(); $updateusername = "UPDATE users SET username = CONCAT(first_name, $id) WHERE user_id = $id"; $Result2 = mysql_query($updateusername, $connalgebra) or die(mysql_error()); // $insertGoTo = "add_user.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } mysql_select_db($database_connalgebra, $connalgebra); $query_rsSchools = "SELECT school_id, school_state, school_city, school_name, school_country FROM schools ORDER BY school_name ASC"; $rsSchools = mysql_query($query_rsSchools, $connalgebra) or die(mysql_error()); $row_rsSchools = mysql_fetch_assoc($rsSchools); $totalRows_rsSchools = mysql_num_rows($rsSchools); Got this script he http://www.codewalkers.com/c/a/Database-Articles/PHPMySQL-News-with-Comments/6/ Everything works, and I mean EVERYTHING. The problem is, when the form gets submitted, the database isn't being queried/updated/whatever. It worked at first, but after I started customizing/modifying it, it quit working. Here's my modified script: Code: [Select] <?php //**********************************// //**********************************// /*******user config variables********/ /* max number of news items to show */ //**********************************// //**********************************// $max_items = 5; //***********************// //***********************// //***********************// //make database connection// //***********************// //***********************// //***********************// $db = mysql_connect ('my hostname','my username','my password'); mysql_select_db ('my database name',$db); //If not all of the news articles are being displayed... function displayNews($all = 0) { /* bring in two variables * $db is our database connection * $max_items is the maximum number * of news items we want to display */ global $db, $max_items; /* query for news items */ if ($all == 0) { /* this query is for up to $max_items; only five news articles will be displayed */ $query = "SELECT id,title,body," . "DATE_FORMAT(date, '%m-%d-%Y') as date " . "FROM news ORDER BY id DESC LIMIT $max_items"; } else { /* this query will get all news; $max_items will be false */ $query = "SELECT id,title,body," . "DATE_FORMAT(date, '%Y-%m-%d') as date " . "FROM news ORDER BY id DESC"; } $result = mysql_query ($query); while ($row = mysql_fetch_assoc ($result)) { /* place table row data in * easier to use variables. * Here we also make sure no * HTML tags, other than the * ones we want are displayed */ $date = $row['date']; $title = htmlentities ($row['title']); $news = nl2br (strip_tags ($row['body'], '<a><b><i><u>')); $url = $row['id']; /* display the data (news) */ echo "<table border=\"0\" width=\"100%\"><tr><td><strong><h2><a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id={$row['id']}\">$title</a></h2></strong> <em>posted on $date</em> | by <strong>DJ Smiley</strong></td></tr>\n"; echo "<tr><td>"; echo stripslashes(substr($news, 0, 500)); echo "...<a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id={$row['id']}\">read more</a></td></tr>\n"; /* get number of comments from database */ $comment_query = "SELECT count(*) FROM comments " . "WHERE news_id={$row['id']}"; $comment_result = mysql_query ($comment_query); $comment_row = mysql_fetch_row($comment_result); /* display number of comments with link; add twitter, facebook, digg, and share widgets; and add email sharing widget */ echo "</table>\n<table width=\"100%\" border=\"0\"> <tr> <td width=\"6%\"><a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id={$row['id']}\"><img src=\"images/Icons/Comment/2.png\" width=\"20\" height=\"20\" class=\"fltlft2\"/></a>$comment_row[0]</td> <td width=\"13%\"><!-- FreeTellaFriend BEGIN --> <a href=\"http://www.freetellafriend.com/tell/\" onclick=\"window.open('http://www.freetellafriend.com/tell/?option=email&heading=Tell+A+Friend&bg=14&url=http%3A%2F%2Fhttp://www.djsmiley.net/index.php?action=show&id={$row['id']}', 'freetellafriend', 'scrollbars=1,menubar=0,width=435,height=500,resizable=1,toolbar=0,location=0,status=0,left='+(screen.width-435)/2+',top='+(screen.height-500)/3);return false;\"><img alt=\"Tell a Friend\" src=\"http://serv1.freetellafriend.com/s14.png\" border=\"0\" /></a> <!-- FreeTellaFriend END --></td> <td width=\"81%\"><span class=\"st_twitter_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Tweet\" st_title=\"{$row['title']}\"></span><span class=\"st_facebook_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\" st_title=\"{$row['title']}\"></span><span class=\"st_email_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Email\"></span><span class=\"st_sharethis_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span></td> </tr> </table><br>"; } /* if we aren't displaying all news, * then give a link to do so */ if ($all == 0) { echo "<br><div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; margin: 5px; background: #F6F6F6;\"></p><a href=\"{$_SERVER['PHP_SELF']}" . "?action=all\">View All Articles</a></p></div>"; } } //function for displaying only one item function displayOneItem($id) { global $db; /* query for item */ $query = "SELECT * FROM news WHERE id=$id"; $result = mysql_query ($query); $row = mysql_fetch_assoc($result); /* easier to read variables and * striping out tags */ $title = htmlentities ($row['title']); $news = nl2br (strip_tags ($row['body'], '<a><b><i><u>')); /* if we get no results back, error out */ if (mysql_num_rows ($result) == 0) { echo "This news article does not exist!\n"; return; } echo "<TABLE border=\"0\" width=\"100%\">\n"; /* displays individual article user visits */ echo "<tr><td><strong><h2><a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id={$row['id']}\">$title</a></h2></strong> <em>posted on $date</em> | by <strong>DJ Smiley</strong></td></tr>\n"; echo "<tr><td>"; echo stripslashes($news); echo "</td></tr>\n"; echo "</table>\n"; echo "<br>\n"; echo ("</table>\n<table width=\"100%\" border=\"0\"> <tr> <td width=\"6%\"><a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id={$row['id']}\"><img src=\"images/Icons/Comment/2.png\" width=\"20\" height=\"20\" class=\"fltlft2\"/></a>$comment_row[0]</td> <td width=\"13%\"><!-- FreeTellaFriend BEGIN --> <a href=\"http://www.freetellafriend.com/tell/\" onclick=\"window.open('http://www.freetellafriend.com/tell/?option=email&heading=Tell+A+Friend&bg=14&url=http%3A%2F%2Fhttp://www.djsmiley.net/index.php?action=show&id={$row['id']}', 'freetellafriend', 'scrollbars=1,menubar=0,width=435,height=500,resizable=1,toolbar=0,location=0,status=0,left='+(screen.width-435)/2+',top='+(screen.height-500)/3);return false;\"><img alt=\"Tell a Friend\" src=\"http://serv1.freetellafriend.com/s14.png\" border=\"0\" /></a> <!-- FreeTellaFriend END --></td> <td width=\"81%\"><span class=\"st_twitter_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Tweet\"></span><span class=\"st_facebook_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span><span class=\"st_email_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Email\"></span><span class=\"st_sharethis_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span></td> </tr> </table>"); /* now show the comments */ displayComments($id); } function displayComments($id) { /* bring db connection variable into scope */ global $db; /* query for comments */ $query = "SELECT * FROM comments WHERE news_id=$id"; $result = mysql_query ($query); echo "<h2>Comments</h2>"; /* display the all the comments */ while ($row = mysql_fetch_assoc ($result)) { //sets variables $comment = strip_tags ($row['comment'], '<a><b&><i><u>'); $comment = nl2br ($comment); $name = htmlentities ($row['name']); $time = ($row['time']); echo "<div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; margin: 5px; background: #F6F6F6;\"><p><table border=\"0\" width=\"100%\"><tr><td><strong>$name</strong> says:</td></tr></table> <table><tr><td><img src=\"images/Icons/People/Anonymous 2.png\" alt=\"\" width=\"50\" height=\"50\"/></td><td>$comment</td></tr></table><table><tr><td>added on $time</td></tr></table></p></div>"; } /* add a form where users can enter new comments */ echo "<form action=\"{$_SERVER['PHP_SELF']}" . "?action=addcomment&id=$id\" method=post> <h2>Comment</h2><table width=\"37%\" border=\"0\"> <tr> <td width=\12%\">Name:</td> <td width=\"88%\"><label> <input type=\"text\" name=\"name\" id=\"name\" class=\"commentBoxforms\"> </label></td> </tr> <tr> <td>Comment:</td> <td><label> <textarea name=\"comment\" id=\"comment\" cols=\"45\" rows=\"5\" class=\"commentField1\"></textarea> </label></td> </tr> <tr> <td> </td> <td><label> <input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Comment\" class=\"Button1\"> </label></td> </tr> </table> </form>\n"; } function addComment($id) { global $db; /* insert the comment */ $query = "INSERT INTO comments " . "VALUES('',$id,'{$_POST['name']}'," . "'{$_POST['comment']}')"; mysql_query($query); echo "Your comment has been posted!<br>\n"; echo "<a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&id=$id\">Return To Previous Page</a>\n"; } /* this is where the script decides what do do */ switch($_GET['action']) { case 'show': displayOneItem($_GET['id']); break; case 'all': displayNews(1); break; case 'addcomment': addComment($_GET['id']); break; default: displayNews(); } ?> Can anyone tell me where this script is going wrong? I've literally tried EVERYTHING. I even went back to the original script and compared every single character to mine, but NO luck. PLEASE HELP! Hi 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)
Hi all, I have another uestion. I am currently working with an XML document that has some comments in it that need to stay however it is messing up my parser that I am working on. How can I get around this issue and make the php parser ignore the comments? here is a snippet of the code I am working on. php Code: [Select] //open XML file containing data for current slide $currentslidefilepath = "slides/xml/"; $currentslidefilepath .= $slides[$currentslide]; $currentSlideXml = simplexml_load_file($currentslidefilepath); XML Quote <!-- there are some comments here --> <Basic> <another>some data</another> </Basic> Hello, I have built a blog in php but. On each article in the blog people are able to comment. I would now like to build a system where people can vote on the comment up/down with Ajax. In my comments database I have a table that looks like this: id / article_id / user_id / dateposted / comment / voteup / votedown I would like it to look like this: Any ideas how I can do this? Tutorials online? Thanks a million I have one small question about comments. say you have a code like this Code: [Select] <?php $lol = 1; $rofl = 2; $lmao = 3; // Above are my variable's echo 'this does not get executed because the apostrophy in the comment acts as the start'; ?> Now if I wrote this code the apostrophe in variable acts as a quote and does not end until it meets another to end it. Why does this do that? I thought that when you start a comment that whole line gets ignored. Could this possible be happening because of my text editor( I use textpad )? If so could you recommend a good text editor, thanks. Hi, i wonna put on my website to ghosts can post comments and registred users, and i made 2 tables ghosts and users, now i need method to save ghosts on that table, but how to save them with uniq number? I tried session_id, but it works bad, when someone comment it write in db his session_id, but after some time, when someone else comment, it can get his session_id, or no ? Is it true that PHP Comments are hidden from end users? And is it dangerous to put extensive comments in your code (e.g. links to developer sites, article excerpts, etc)? I am re-factoring my website, and have found some really helpful articles that I'd like to post in my code so I don't forget what I'm doing 6 months from now, but don't want to cause any issues. (I know this sounds wimpy, but I am a newbie?!) Debbie Hey guys not sure if this is the right spot for this 100% but I hope it is. I have a website that I'm making for a class project and I would like it to be a Movie Review type site. What I want to happen is that a person searches for the movie, and once if they find the movie it goes to another page saying if it was found or not. And if it was found information of the movie would come up. I made a comment section for people to be able to post what they thought about the movie. (It doesn't work yet but it should be up soon) But anyway how would I make it so like say a person searches for "avatar" and the movie pops up with the information, that the review is for avatar and only avatar. Then next they search for Lord of the rings, and only lord of the rings reviews pop up? And just to let ya know I'm not a super coder with this stuff and I am using dreamweaver cs5 to do a lot of the coding. Any and all help would be appreciated. ok here is my script , for some reason , it adds the comment and all it works great , but it wont add it to the notifications table in my database Code: [Select] <?php include("../includes.php"); $session = $logOptions_id; if($session) { $to_id = $_POST['user_id']; $post_id = $_POST['post_id']; $comment = mysql_real_escape_string($_POST['comment']); $date = mktime(); mysql_query("INSERT INTO comments SET user_id='$to_id', from_id='$session', post_id='$post_id', comment='$comment', date='$date'"); $id = mysql_insert_id(); $query = mysql_query("SELECT * FROM comments WHERE post_id='$post_id' AND from_id!='$session' AND state='0' GROUP BY from_id"); if(mysql_num_rows($query)>0) { $row1 = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE id='$post_id'")); $post_from2 = $row1['from_id']; mysql_query("INSERT INTO notifications SET user_id='$post_from2', from_id='$session', post_id='$id', action_type='4', date='$date'"); while($row = mysql_fetch_array($query)) { $post_from = $row['from_id']; if($post_from!=$post_from2) { mysql_query("INSERT INTO notifications SET user_id='$post_from', from_id='$session', post_id='$id', action_type='4', date='$date'"); } } } else { $row1 = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE id='$post_id'")); $post_from = $row1['from_id']; mysql_query("INSERT INTO notifications SET user_id='$post_from', from_id='$session', post_id='$id', action_type='4', date='$date'"); } $query = mysql_query("SELECT * FROM comments WHERE id='$id' AND state='0'"); comments($query); } ?> What does this code do/mean? /* * @the vars array * @access private */ TomTees What is the best RegEx to use for a Comments field? I suppose I would like people to be able to enter any characters found on an English keyboard. (Is that too lax?) Should I restrict any particular characters like quotes? I am asking this question from two standpoints... 1.) It's a pain to create a Regex that has ever character on your keyboard typed out! 2.) From a security standpoint, I'm not sure what to allow?! Thanks, Debbie Hello, So I am trying to reduce my memory footprint to the lowest possible value without sacrificing functionality. I noticed that if I write a comment that is 2kb long, it costs me 2kb more memory to run the script. How can I get PHP to free the memory taken up by comments? It seems like it would be a real pain in the butt to have to run php -w on all my source files each time I update my server. Any ideas? Thanks. David I'm trying to get my head around oop and wondered if anyone would look at my comments so far . I want to learn a bit about constructors next but thought I should make sure I understand the below code properly first. Code: [Select] <?php class Dictionary { //new class public $translations = array(); public $type =" "; //new variables called 'PROPERTIES' function summarize() { //function within a class is called a 'METHOD' $ret = "Dictionary type: {$this->type}\n"; // {$this->type} means: use $type which is found within THIS class $ret .= "Terms: ".count( $this->translations )."\n"; // {$this->type} means: count the length of the $translation array which is found within THIS class return $ret; } } ?> Code: [Select] <?php include('class_dictionary.php'); //include file that holds the class $english = new Dictionary; // creating new object using the class called Dictionary $english->type = "EN"; // adding a value to the 'type' property located within the dictionary class $english->translations['TREE'] = "branch"; //adding TREE key and value branch to the translations array $english->translations['TREEtwo'] = "trunk"; //adding TREEtwo key and value trunk to the translations array $french = new Dictionary; //creating a new instance of the Dictionary object $french->type = "FR"; $french->translations['TREE'] = "arbre"; print_r( $english ); echo "<br/>"; print $english->summarize(); //prints the summarize method ?> Hey there - I have been trying to limit the number of comments a user can make per day on my social network. Thanks to great help on here I am getting really close, however, there are some bugs that have me banging my head against the wall. I am able to limit, but now, its 1. not limiting PER day and limiting all around ( meaning: I can't make any comments at all today ) 2. it is limiting for EVERY user as opposed to limiting a specific user Here is the code I have: Code: [Select] if(isset($_POST['commentProfileSubmit'])) { if($_POST['ProfileComment'] == "" || $_POST['ProfileComment'] == "Tell the community what's on your mind...") { $valid = false; $error_msgs_comments[] = "Whoops! You forgot to write your airwave."; }else{ if($_POST['ProfileComment'] == "" || $_POST['ProfileComment'] == "Leave ".$prof->first_name." a comment here...") { $valid = false; $error_msgs_comments[] = "Whoops! You forgot to write your comment."; }else{ /* if the person signed in is NOT the profile */ $query = "SELECT * FROM `cysticUsers` WHERE `id` = '" . $prof->id . "'"; $request = mysql_query($query,$connection) or die(mysql_error()); $result = mysql_fetch_array($request); $max_post_per_day = 5; $Email = $result['Email']; $check_profi = $result['check_profi']; $check_reply = $result['check_reply']; if($prof->id != $auth->id && $check_profi == 'checked' && $max_post_per_day < 5) { $to = $Email; $subject = "$auth->first_name $auth->last_name commented on your profile on CysticLife"; $message = "$auth->first_name $auth->last_name commented on your profile on CysticLife: <br /><br />\"$body\"<br /><br /> <a href='http://www.cysticlife.org/Profile_build.php?id=" . $prof->id . "'>Click here to view</a><br /><br />Do LIFE,<br /> The CysticLife Team"; $from = "CysticLife <noreply@cysticlife.org>"; $headers = 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n"; $headers .= "From: $from"; mail($to, $subject, $message, $headers); } $query = "SELECT COUNT(*) FROM `CysticAirwaves` WHERE `FromUserID` = $auth->id AND `date` = CURDATE()"; $result = mysql_query($query, $connection); $post_count = mysql_result($result, 0); if($post_count >= $max_posts_per_day) { echo "You have reached the maximum number of posts for the day. Try again tomorrow"; } else { $comment = mysql_real_escape_string($_POST['ProfileComment']); $query = "INSERT INTO `CysticAirwaves` (`FromUserID`, `ToUserID`, `comment`, `status`, `statusCommentAirwave`, `date`, `time`) VALUES ('{$auth->id}', '{$prof->id}', '{$comment}', 'active', 'active', CURDATE(), CURTIME())"; mysql_query($query, $connection) or die(mysql_error()); } if($auth->id == $prof->id) { $just_inserted = mysql_insert_id(); $query = "UPDATE `CysticAirwaves` SET `status` = 'dead' WHERE `FromUserID` = '" . $auth->id . "' AND `ToUserID` = '" . $prof->id . "' AND `id` != '" . $just_inserted . "'"; $request = mysql_query($query,$connection); } } } } thanks so much in advanced I added the ability for Users to "preview" their Comments before submitting them. I just realized that when they click "Preview" that their Comments appear above the Comments form box - similar to how PHPFreaks works - but that the Comments form box loses it's data since the page reload causes this to lose things... <li> <label for="comments">Comments:</label> <textarea id="comments" name="comments" cols="50" rows="15"><?php if (isset($comments)){echo nl2br(htmlentities($comments, ENT_QUOTES));} ?></textarea> <?php if (!empty($errors['comments'])){ echo '<span class="error">' . $errors['comments'] . '</span>'; } ?> </li> What is the easiest way to maintain form persistence? (I really would like to avoid having to store things in my database during the preview.) How does PHPFreaks do things? I was going to use a SESSION, but since this is a Comments field that can take up to 65,535 characters, that probably won't work?! Any ideas? Debbie I need help getting user comments from my database and displaying them in a format like you'd see in an online newspaper where each user's comments are displayed one after the other like this... Quote --------------------- By John Doe 8:30 p.m. on Sept 1, 2011 I really liked Debbie's article and encourage others to read it! --------------------- By Sally Peters 11:00 a.m. on Aug 30, 2011 I had the same thing happen to me!! --------------------- Here is the code I have on my "article.php" page below where I generate my Article... Code: [Select] // ********************** // Build Comments Query * // ********************** // Build query. $q = 'SELECT m.first_name, c.created_on, c.body, c.status FROM member AS m INNER JOIN comment AS c ON m.id = c.member_id WHERE article_id=?'; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variable. mysqli_stmt_bind_param($stmt, 'i', $articleID); // Execute query. mysqli_stmt_execute($stmt); // Store result-set. mysqli_stmt_store_result($stmt); // **************************** // Check for Comments Record. * // **************************** if (mysqli_stmt_num_rows($stmt)>=1){ // Comment in Database. $commentExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $firstName, $createdOn, $body, $status); // Fetch record. mysqli_stmt_fetch($stmt); } Is it correct that mysqli_stmt_store_result($stmt); stores the entire query results? Where does it do that? Some hidden MySQL object in memory? How do I get the query results into a format where I can iterate through each record and display it? Thanks, Debbie Hey guys i have been making a comment and reply script. When the user makes a post and others reply they appear below. However when another person makes a post and a reply is made to that they mess up it has the comments at the top and the replys at the bottom. DOes anyone know how i could order these? Or is there a tutorial online. Hope someone can help. Thanks |