Search
Left Quote    Every day I get up and look through the Forbes list of the richest people in America. If I
- Robert Orben    
Right Quote
 
[login] | [Register]
 

Building a Comments Script

by: bs0d
Page: 4 of 4
(View All)

Displaying the Form


We are nearing the end, and this is our last portion of code. Under the condition that checks if the submit button is pressed, this is our "else" part. Its not pressed, so we display the form. Here is the first part:



In the code above, you see the else part of the condition to begin displaying the form, and the html which starts the form and where we declare our hidden fields. We have three hidden fields: page, date and time. These fields are not shown to the user, we use them internally to get that data. The data is inserted in the value property with PHP.

Displaying the Form Continued...


This is the rest of the form, which goes immediatley under the code displayed above. It is simply a table with form elements for the user to input data. Again, you can add colors and formatting later, this is basically what you will need.


Conclusion


You can cut and paste each of all the code sniplets within this tutorial, or you can get the entire script from the code samples area. To view it, follow the link below:

Comments Script Code

There we have it. I've walked you through step by step of creating a comments system for your website. With this comments script, it is run easily through a database, and can have comments on countless pages. If you have a users system, then it will be very easy for you to see if they're logged in and display their member name in the username field. I hope this tutorial has served you well! Enjoy-

bs0d | www.allsyntax.com

1  |  2  |  3  |  4  |  


Comments:

  gravy
  Subject: "Awesome" Date: Mar 08 2007 at 5:27 pm    

I ca't wait to digg into this code work ow that I have read the tutorial! Great job!
  curious
  Subject: "reverse order; queuing posts" Date: Sep 06 2007 at 8:25 am    
I will be re-reading more carefully to see if you discuss this, but am interested to know whether the posts can be shown in reverse order (latest post first) and whether the posts can be held in queue and be made live only after the moderator has approved them.
  curious
  Subject: "Thanks" Date: Sep 06 2007 at 8:27 am    
Many thanks for the tutorial, by the way. I really appreciate it.
  bs0d
  Subject: "Sure Thing" Date: Sep 10 2007 at 12:41 pm    

You can change the order of the posts easy enough. Just change from ASC to DESC in the end of the query that grab's the posts (on page 2 of this article).

You can also hold them in "queue&q uot; simple enough. Add a column to the table, call it "verify& quot; - you can set it up to be enum ('yes', 'no') with default as no. Then, when you query, query all where verify = yes.

You can make moderators able to see all posts (yes or no), just execute a different query if they're logged in and are moderator. Add a link in the corner of unverified posts that only moderators can see to verify the posts. That link would be to a script that updates the verify column for the post from no to yes.
  chinako
  Subject: "MySQL" Date: Sep 26 2007 at 10:18 pm    
I love this! As a brand newbie to PHP I find this code and its breakdown to be very helpful.

My question lays within the use of MySQL to get this code functioning properly. As my host does support PHP I asked them about MySQL and they told me that I would need a MySQL database for it, as they don't have one. Is the one we are building with this code all I need, or do I need a "database " that is its own code?

Thank you for taking the time to answer my question! Again, I'm brand new to PHP and MySQL, so I apologize for this if it seems simple.
  bs0d
  Subject: "Database Required" Date: Sep 27 2007 at 7:27 am    

Yes, you need a database. This article talks about creating a table IN the database, so they would need to install mySQL. Actually, it's very rare for a hosting company to have PHP and not MySQL or any other database available.
  chinako
  Subject: "Code Goes Where" Date: Sep 27 2007 at 9:09 am    
Thank you! I'll look into the database issue.

Another question I have is simply where do I put this code? Does it need to go within the HTML pages that require comments? Or is there a link I can add to every blog entry that would point to the comment PHP code as its own page, thus giving me comments for each blog?

Also, how do I tell the code which comments go to which entry? Is there a space for me to program dates of entries so that the comments only show up for the entry they are about?

Again, sorry for so many questions. But thank you very much for your help!
  bs0d
  Subject: "Check the Forums or Search" Date: Sep 27 2007 at 9:54 am    

You can check the fourms, or use the search feature in the top-right corner of the site.

Here is a topic that answers your question: PHP Comments Script Question
  chinako
  Subject: "Thanks Again!" Date: Sep 28 2007 at 10:38 am    
Thank you SO much! You are a wonderful help and I really appreciate that you took the time to type all this out as well as answer questions.

Have a GREAT day!
  PyroCandy
  Subject: "Getting Errors" Date: Mar 07 2008 at 8:29 pm    
I could use some help once again . . .

I have the db created in mySQL and put the script code into my page . . .but when I try to load the page it give me a PHP error message right on the page.

pyrocandy.890m. com/comments.ph p

plz and ty for all your help
hope to hear from you soon
  jyogit
  Subject: "help needed" Date: Mar 19 2008 at 4:02 am    
well ive created the dbase and copied and pasted the code.
on the final full code u have ommited the first line of the connect once code....

i cant get this to work at all.

am i missing something?
  cefx
  Subject: "customize" Date: Jun 19 2008 at 1:53 pm    
is there anyway i can customize the out come of the comment... i.e. wat it looks like?


  bs0d
  Subject: "Yes" Date: Jun 19 2008 at 7:35 pm    

Yes, the outcome of the comment is up to your creativity with HTML/CSS.
  serdas
  Subject: "how would see if they're logged in..." Date: Feb 04 2009 at 8:00 am    
"If you have a users system, then it will be very easy for you to see if they're logged in and display their member name in the username field"

how would i do that?
  craig
  Subject: "Getting Access Denied" Date: Jun 23 2009 at 8:32 am    
I've pasted your script into a file called Comments.php but when I access that page I get the error messages below:

<
Warning: mysql_query() [function.mysql -query]: Access denied for user: 'craig@localho st' (Using password: NO) in /home/craig/www /www/Comments.p hp on line 12

Warning: mysql_query() [function.mysql -query]: A link to the server could not be established in /home/craig/www /www/Comments.p hp on line 12
Access denied for user: 'craig@localho st' (Using password: NO)

Can you point me to where I've gone wrong?

Thanks!
  bs0d
  Subject: "db_connect" Date: Jun 23 2009 at 4:06 pm    

Sounds like you've won 1/2 the battle. Remember to connect to the database first: PHP - Connect to Database
  deflipp
  Subject: "Comment isn't being reposted?" Date: Apr 21 2010 at 2:24 pm    
I have been looking for this type of tutorial FOREVER! It was SOOOO helpful!

Anyway, I have followed your script, but when i submit the comments, they don't want to post... The page refreshes and remains the same. When I go to phpMyAdmin, it says the table is empty. What could I have done wrong?

Here is the code for my test page:


Code:

<!DOCTYPE html PUBLIC "-//W3C// DTD XHTML 1.0 Transitional//E N"

"http://w ww.w3.org/TR/xh tml1/DTD/xhtml1 -transitional.d td">
<html xmlns="ht tp://www.w3.org /1999/xhtml&qu ot;>
<head>
<meta http-equiv=&qu ot;content-type " content=" text/html; carset=utf-8&q uot; />
<meta name="des cription" content=" A research collaboration on the country Russia and its totalitarian roots for a jYork group project stemming from George Orwell's 1984." />
<meta name="key words" content=" russia, totalitarian, research, george orwell, 1984, regime, soviet union, USSR, project" />
<title>T he Russia Project- A YorkBrit 1984 Research Collaboration&l t;/title>
<link rel="styl esheet" type="tex t/css" href="trp .css" />
</head> <body>
<img class="bg img" src="ussr and russia flag.png" alt="&qu ot; />
<div class="wr ap"> <div class="he ader">
<img class="he aderimg" src="trph eader.png" ; alt="The Russia Project: A YorkBrit 1984 Research Collaboration& quot; />
</div>
<div class="me nubar"> ;
<table class="me nubar" cellpadding=&q uot;0px" cellspacing=&q uot;0px"& gt;
<tr>
<td id="lefte ndcap"> ;&nbsp;< /td>
<td> <a href="ind ex.html" id="home "><s pan>Home< /span></a >
</td>
<td> <a href="uss r.html" id="ussr "><s pan>U.S.S.R. </span>&l t;/a>
</td>< br /> <td> <a href="rus sia.html" id="russi a">< ;span>Russia </span>&l t;/a>
</td>< br /> <td> <a href="wor kscited.html&q uot; id="works cited"> ;<span>Wo rks Cited</span& gt;</a> </td>< br /> <td id="right endcap"&g t;&nbsp;< ;/td>
</tr> </table>
</div>
<center>< br /> <div class="co ntent"> ;
<h1 class="pa ge-title" >COMMENT TEST PAGE</h1>
<br />
<hr id="artic le_comment_brea k" noshade />
<?php
require_once($_ SERVER['DOCUME NT_ROOT']. '/database_con nect.php');
//querying comments for this article
$inf = "SELECT * FROM `comments` WHERE page = '".strip slashes($_SERVE R['REQUEST_URI '])."' ORDER BY time";
$info = mysql_query($in f) or die ( mysql_error() );
if( mysql_num_rows( $info ) != 0 ) {
echo '<h3 class="co mments"&g t;Comments:< /h3>';
echo '<table class="co mments"&g t;';
while ( $info2 = mysql_fetch_obj ect( $info ) ) {
echo '<tr>';
echo '<td>'. htmlspecialchar s(stripslashes( $info2->subj ect)).'" by: <a href="'. $info2->cont act.'"&g t;'.htmlspecia lchars(stripsla shes($info2-> ;username)).'& lt;/a></t d><td> <div> @ '.date('h:is a', $info2->time ).' on '.$info21-> date.'</div ></td> ';
echo '</tr>&l t;tr>';
echo '<td colspan=" 2"> '.htmlspecialc hars(stripslash es(n12br($info2 ->comment))) .' </td>';< br /> echo '</tr>' ;
} // end while
echo '</table> ;';
echo '<hr noshade width="50 0px" align="ce nter" />';
}
else echo 'No comments for this page. Feel free to be the first. <br />';
if (isset($_POST[ 'submit'])) {
if(!addslashes ($_POST['usern ame'])) {
die('<u&g t;ERROR:</u& gt; You must enter an alias to comment.');
}
if(!addslashes ($_POST['conta ct'])) {
die('<u&g t;ERROR:</u& gt; Please enter an email or URL to comment.');
}
if(!addslashes ($_POST['subje ct'])) {
die('<u&g t;ERROR:</u& gt; Please give your comment a subject.');
}
if(!addslashes ($_POST['comme nt'])) {
die('You <u>must&l t;/u> enter a comment in order to comment (DUH!).');
}
// this is for a valid contact
if(substr($_PO ST['contact'] ,0,7) != 'mailto:' && !strstr($_POST[ 'contact'],' //')) {
$_POST['cont act'] = "mailto: ".$_POST[ 'contact'].&q uot;";
}
else {
$_POST['cont act'] = "http:// ".$_POST[ 'contact'].&q uot;";
}
// end valid contact

//add comment
$q = "INSERT INTO `comments` VALUES ('".$_GE T['id'].&quo t;', '".$_POS T['page'].&q uot;', '".$_POS T['date'].&q uot;', '".$_POS T['time'].&q uot;', '".addsl ashes(htmlspeci alchars($_POST[ 'username'])) ."', '".$_SER VER['REMOTE_AD DR']."' , '".addsl ashes(htmlspeci alcharacters($_ POST['contact ']))."', '".addsl ashes(htmlspeci alchars($_POST[ 'subject'])). "', '".addsl ashes(nl2br(htm lspecialchars($ _POST['comment '])))." ')";
$q2 = mysql_query($q) ;
if(!$q2) die(mysql_error ());

//refresh page so they can see new comment
header('Locati on: http://' . $_SERVER['HTTP _HOST'] . $_POST['page' ] . "#comment s");

}
else { //display form
?>

<form name="com ments" action="& lt;?php $_SERVER['PHP_ SELF']; ?>" method="p ost">< br />
<input type="hid den" name="pag e" value="&l t;?php echo($_SERVER[ 'REQUEST_URI'] ); ?>"> ;
<input type="hid den" name="dat e" value="&l t;?php echo(date()); ?>"> ;
<input type="hid den" name="dat e" value="&l t;?php echo (time()); ?>"> ;
<div class="fo rm_fields" ; >
<label> Alias:</labe l><input type="tex t" name="use rname" size="30 "><b r />
<label> Subject:</la bel><inpu t type="tex t" name="sub ject" size="30 "><b r />
<label> Email or URL:</label& gt;<input type="tex t" name="con tact" size="30 "><b r />
<label> Message:</la bel><text area name="com ment" rows="5& quot; cols="24 "></ textarea>< ;br />
<input type="sub mit" value="Po st Comment" />
</div> <?php
} //end else
?>
</div> </div>
</center>
<div class="fo oter">
<p class="fo oter"> Design &copy;2010 Scriptech Designs &bull; Content &copy;2010 YorkBrit English 11-4</p>< br /> </div>
</div>
</body> </html>



I also want to know if you know of a good CAPTCHA resource, as I think that type of addition would be a good idea.... but I don't know....
  bs0d
  Subject: "Hmmm" Date: Apr 22 2010 at 9:43 am    

I didn't notice anything immediately in your code. It looks like you have some error handling if the query fails... are you using the right table name in the query to match what is in the database? If phpMyAdmin shows nothing, then it's not inserting the comment in the DB, which would explain why your page shows nothing.

There is a CAPTCHA code on our site here.
  kyosama66
  Subject: "Parsing error" Date: Oct 29 2010 at 9:09 pm    
I've got everything worked out, users can post and comments are displayed, however, linebreaks are not being parsed correctly.
Example:
"AWESOME. The system WORKS and you partially agreed.<br /> WTF is with all those tags? seems like a parsing error.<br /> MUST FIX. "
  bs0d
  Subject: "nl2br" Date: Oct 30 2010 at 2:27 pm    

You may need to change the order of the functions when the comment is added to the DB: addslashes(html specialchars(nl 2br($_POST['co mment'])))

  kyosama66
  Subject: "Fixed!" Date: Oct 31 2010 at 12:04 am    
That did it! The code is now:


Code:
'".adds lashes(nl2br(ht mlspecialchars( $_POST['commen t'])))." ')"



This caused the text to be entered into my database so that it would be interpreted as clean linebreaks.

The only problem now is that when the page refreshes, the new comments don't show. The old ones are there, but not the one just posted. It won't show the entry form either. Does there need to be some sort of delay to allow for processing?
  bs0d
  Subject: "Show post" Date: Nov 02 2010 at 10:35 am    

The code adds the data to the database, and refreshes the page that queries the comments, so it should appear... does it show up when you refresh a 2nd time?
  kyosama66
  Subject: "Show Post" Date: Nov 04 2010 at 4:20 pm    
Yes, it does show up after the 2nd time.
  bs0d
  Subject: "Note sure" Date: Nov 08 2010 at 7:17 pm    

Not sure what the answer is here... sometimes people will get warnings from PHP indicating the headers were already sent. In that case, you would include ob_start(); as the first line of the code. But your script is adding the comment... so again, I'm not sure what your exact problem is. You can email the code to me and I can take a look.
  kyosama66
  Subject: "sent" Date: Nov 09 2010 at 12:55 am    
I sent an email with my current comments.php script and a few links so you can give it a try on my site. Hopefully, you'll be able to reproduce the problems.
  ilezia
  Subject: "Timestamp" Date: Jul 19 2011 at 1:02 am    
Hi,

first of all thanks for this tutorial. I've got a task to build a website but have no prior programming experience so these kind of tutorials really make the task possible!

Then for my actual question. Does the form fill the timestamp automatically from the server? I've got it running in basic form now but all the messages I send are -7 hours compared to my own time, which could mean that it picks up the time from the server (which are located in the US while I'm in Europe).

Is there a way for me to change this?

Regards,
Ilkka
  bs0d
  Subject: "Timestamp" Date: Jul 20 2011 at 12:11 pm    

ilezia - you can modify the time however you like. Take a look at PHP.Net - Time
  ilezia
  Subject: "Refresh just part of the page" Date: Aug 10 2011 at 3:37 am    
Thanks bs0d, got that one working.

I've got another question, however. I'm loading my comments board into a div from an external file. I have a drop down menu from which the user chooses the topic and via AJAX I load gettopic.php?t= topic. The current code refreshes the whole page when a new comment is added.

header('Locati on:http://' . $_SERVER['HTTP _HOST'] . $_SERVER['REQU EST_URI']);

How would I make it so it only refreshes the contents within the div as I have other elements in the page (zoomable/panna ble svg graphics, don't want to loose users loc) that I don't want to refresh?
You Must be logged in or a member to comment.


Tutorial Stats

Tutorial Stats

313,339 Views
41 Total Comments
4.75 Rating of 5 (4 Votes)

Options

Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Del.icio.us: Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article

Articles

Related    

· Simple PHP Tutorial
· One File Website
· Pagination with PHP
· Complete Members System
· Variable Scope


"AllSyntax.com" Copyright © 2002-2014; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank