PHP Code for Add Forum Reply to Database
Forums are great communication tools for the exchange of ideas, for people teaching others about a specific area of interest, or even for just general social communication. The fact that they are usually so specialized helps get them high up in search results as well as contributing considerably to bodies of knowledge. True, there's a lot of misinformation and putdowns, but this invariably occurs when people communicate. One must learn to take what one learns with a grain of salt.
On to the PHP code. As usual, we start with config.php, since without it, the MySQL-based forum would not be viable. You cannot relate to a db without knowing the magic words. Next, the security of the page is dealt with by ensuring the page visitor has a username that's in the database. Note that the various pages on our forum app use both forms and URL query strings to transfer data between pages, so both POST and GET are checked for username, and if neither works, the visitor is sent to the login script. Not only is the db checked for a valid username, the username is checked to make sure it has only 6 to 20 letters, numbers or underscore in it and no other characters—otherwise, it's off to the login script. If a hacker has put something nasty in the query string, he'll end up at the login script. All our forum app scripts have this same username checker at the top of the PHP section—except for the login script.
After getting the POSTed id of the topic being replied to, the db forum_answer table is queried for the highest numbered reply relating to the current topic with the use of SQL's MAX() function. Reply ids are in the a_id field. The new reply this script is dealing with is given an id one higher than the highest id number found. The a_name, a_email, and a_datetime fields will be POSTed into this script and inserted into the table, and the question_id and a_id fields will be inserted as well, but the main content will be in the a_answer field. The name, email, and reply POSTed to the script get the mysql_real_escape_string() function run on them, with name and email getting it as it's POSTed but the reply getting it right before it goes into the db. The strip_tags() and htmlspecialchars() functions are run on the name and email but the reply itself gets only strip_tags() and the preg_replace() function to filter out unwanted characters. The following characters are allowed in the reply, which goes in the a_answer field: a-z A-Z 0-9 . , ! ; - _ " ? ' : ( ) / and space. It's a good thing the mysql_real_escape_string() function is run before the data gets into the db. Since some of the allowed characters—especially single quote—can be used to exploit and harm MySQL databases, we need to escape them. The preg_match() function is run on both the name and email and input validation is thereby accomplished. After a MySQL query INSERTs this new reply into the db table forum_answer, the forum_question table gets its reply field updated. This field just keeps track of how many replies a topic has gotten, which it displays on the forum home page.
SAVE THIS PAGE AS: cms-add-answer.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Add Forum Reply—Content Management System (CMS)</TITLE>
<meta name="description" content="Add Forum Reply—Content Management System (CMS)">
<meta name="keywords" content="forums,forum,Content Management System,Content Management System Articles,php,CMS,javascript, dhtml, DHTML">
</head>
<body>
<?php
include_once"config.php";
$U=$_POST['username'];if (!isset($U)){$U=$_GET['username'];}
if (isset($U)&&preg_match("/[A-Za-z0-9_]{6,20}$/",$U)){$check_user_data = mysql_query("SELECT * FROM members WHERE username='$U'") or die(mysql_error());if(mysql_num_rows($check_user_data)==0){unset($U);}}else{unset($U);}
if (!isset($U)){echo '<script language="javascript">alert("Please login.");window.location="login.php"; </script>';}
$tbl_name="forum_answer";
$id=mysql_real_escape_string($_POST['id']);
$sql="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
if ($rows) {$Max_id = $rows['Maxa_id']+1;}
else {$Max_id = 1;}
$a_name=mysql_real_escape_string(substr($_POST['a_name'],0,65));
$a_email=mysql_real_escape_string(substr($_POST['a_email'],0,65));
$a_answer=substr($_POST['a_answer'],0,10000);
$datetime=date("d/m/y H:i:s");
$a_name = strip_tags($a_name);
$a_name = htmlspecialchars($a_name, ENT_QUOTES);
if (!preg_match("/[A-Za-z0-9_ ]{6,20}$/",$a_name)) {
echo '<script language="javascript">alert("Please enter 6 to 20 letters, space, numbers and underline for name."); window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';}
$a_email = strip_tags($a_email);
$a_email = htmlspecialchars($a_email, ENT_QUOTES);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$a_email)) {
echo '<script language="javascript">alert("That email address is not valid."); window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';}
$a_answer = strip_tags($a_answer);
$pattern2 = '/[^a-zA-Z0-9\\s\\.\\,\\!\\;\\-\\_\\"\\?\\047\\:\\(\\)\\057]/i';
$a_answer=preg_replace($pattern2, "", $a_answer);
$a_answer=mysql_real_escape_string($a_answer);
if (strlen($a_answer)<6) {
echo '<script language="javascript">alert("Please enter 6 to 10000 characters for reply."); window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';
}else{
$sql2="INSERT INTO $tbl_name(id, question_id, a_id, a_name, a_email, a_answer, a_datetime)
VALUES('', '$id', '$Max_id', '$a_name', '$a_email', '$a_answer', '$datetime')";
$result2=mysql_query($sql2);
if($result2){
$tbl_name2="forum_question";
$sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'";
$result3=mysql_query($sql3);
echo '<script language="javascript">window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';
}else{echo '<script language="javascript">alert("ERROR updating database tables"); window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';}
}
mysql_close();
?>
</body>
</html>