Comment System with MySQL
This tutorial will show you how to code a full comment system for your site. Well, lets get started, shall we?
Run this query through PHPMyAdmin
Code
CREATE TABLE `comtbl` (
`postID` INT NOT NULL AUTO_INCREMENT ,
`postTITLE` TEXT NOT NULL ,
`posterNAME` TEXT NOT NULL ,
`posterEMAIL` TEXT NOT NULL ,
`postTIME` TIMESTAMP NOT NULL ,
`postTXT` TEXT NOT NULL ,
PRIMARY KEY ( `postID` )
);
Start a new page and name it commentform.html and insert this code:
Code
<form action="commentadd.php" method=post> <input type="text" name="poster" size="23" value="name"><br /> <input type="text" name="posttitle" size="23" value="name"><br /> <input type="text" name="postemail" size="23" value="user@email.com"><br /> <textarea cols=44 rows=6 name="posttxt" size=24 wrap="VIRTUAL">message</textarea><br /> <input type=hidden name=assume value=true> <input type="submit" value="Add Comment">
index.php
PHP Code
<? $dbcnx = mysql_connect("host", "username", "password"); //connects mysql_select_db("comments"); $result = @mysql_query("SELECT * FROM comtbl ORDER BY postID DESC"); if (!$result) {/grabs comments from db
echo("<b>Error performing query: " . mysql_error() . "</b>"); exit(); } while ($row = mysql_fetch_array($result) ) { $msgTxt = $row["postTXT"]; $msgId = $row["postID"]; $SigName = $row["posterNAME"]; $SigDate = $row["postTIME"]; $msgTitle = $row["postTITLE"]; $url = $row["posterEMAIL"]; $yr = substr($SigDate, 2, 2); $mo = substr($SigDate, 4, 2); $da = substr($SigDate, 6, 2); $hr = substr($SigDate, 8, 2); $min = substr($SigDate, 10, 2); if ($hr > "11") { $x = "12"; $timetype = "PM"; $hr = $hr - 12; }else{ $timetype = "AM"; } if (!$url) { $url = "#"; }else{ $stat = $url; $url = "mailto:" . $url . ""; } echo("<p><b>$msgTitle</b> $msgTxt<br><div align=right> $hr:$min $timetype | $mo/$da/$yr | $msgId, <a href='$url'>$SigName</a></div></p>"); } ?>
commentadd.php
PHP Code
<? $assume = $_POST['assume']; $posterEMAIL = $_POST['postemail']; $postTXT = $_POST['posttxt']; $posterNAME = $_POST['poster']; $postTITLE = $_POST['posttitle']; if ($assume == "true") { $dbcnx = mysql_connect("host", "username", "password"); mysql_select_db("comments"); $sql = "INSERT INTO comtbl SET posterNAME='$posterNAME', posterEMAIL='$posterEMAIL', postTXT='$postTXT', postTITLE='$postTITLE'"; if (mysql_query($sql)) { echo(" Your comment has been added "); } else { echo(" Error adding entry: " . mysql_error() . " "); } } ?> <script language=javascript> <!-- location.href="index.php"; //--> </script>
Well, you're finished :D. I have a live preview here. Sorry it's not commented, it's hard to comment in this box I'm typing the tutorial in. lol.
NOTE: The live preview is edited to my likings with a CSS stylesheet added to make it look better. With the code above, your comment system will not turn out like mine without proper editing.