PHP Code for Edit Forum Topic in 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.
First, there is a JavaScript function textCounter() that keeps track of your character count, displays it on the screen, and even dumps any excess characters once your character count reaches 10,000.
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.
Then we get the POSTed flag, detail, and id data. The id is the id of the topic being edited in the db, the flag is a flag meaning the input form was submitted, and detail is a field in the topic table in the db, forum_question.
The way the script works is first the POSTed detail data is checked and if it's not set because the user just arrived in this script, it loads the $detail string from the db, not forgetting to run strip_tags() and stripslashes() on this string as well. Then the db is checked to see who the topics_username is and if it's not the user attempting to edit the topic, he gets a message: "You must be the topic author to edit this topic." But if he is the user that wrote it, the HTML form is shown and this is a textarea input box with the just-found detail data in it. Well, it's almost in it. Another JavaScript routine must be run first, and this one is:
var c = <?php echo json_encode($detail); ?>; if (c != null && c!=""){document.form1.detail.value=c;}, which grabs the just-loaded data from the PHP $detail string and converts it to JavaScript, after which it loads the detail field in the form. This JavaScript code comes up immediately after the form appears, so it looks like the form appears fully loaded.
Once the editing is done and the submit button clicked, it reloads the page and both the JavaScript function already discussed and the PHP routine used as a filter and validator will be trimming detail to 10,000 characters if it tries to get longer. The strip_tags() function is run, and the preg_replace() function is run to filter out unwanted characters. The following characters are allowed in detail (the main topic content): a-z A-Z 0-9 . , ! ; - _ " ? ' : ( ) / and space. (The 047 and 057 in the preg_replace() below are single quote and forward slash, by the way.) The detail input data gets the mysql_real_escape_string() function run on it right before it goes into the db. It's a good thing the mysql_real_escape_string() function is run, since some of the allowed characters—especially single quote—can be used to exploit and harm MySQL databases, so we need to escape them. Anyway, if the flag has been set because the form was submitted, both the detail and the datetime field are now UPDATEd in the db.
SAVE THIS PAGE AS: cms-edit-topic.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>Edit Forum Topic—Content Management System (CMS)</TITLE>
<meta name="description" content="Edit Forum Topic—Content Management System (CMS)">
<meta name="keywords" content="forums,forum,Content Management System,Content Management System Articles,php,CMS,javascript, dhtml, DHTML">
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-color:#ccc}
p, li {font:13px Verdana; color:black;text-align:left}
h1 {font:bold 28px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
td {font:normal 13px Verdana;text-align:left;background-color:#eee}
.topic {text-align:left;background-color:#fff}
.mid {text-align:center;background-color:#aaa}
.right {text-align:right;}
.form {position:absolute;top:140px;left:150px;width:704px;border:1px solid blue;padding:6px;background-color:#eee}
.info {position:absolute;top:19px;left:2px;width:128px;border:1px solid blue;padding:6px;background-color:#bbb}
</style>
<script type="text/javascript">
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit){field.value = field.value.substring(0, maxlimit);}
else{countfield.value = maxlimit - field.value.length;}}
</script>
</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>';}
$flag=$_POST['flag'];
$detail=$_POST['detail'];
$tbl_name="forum_question";
$id=mysql_real_escape_string($_GET['id']);
if(!isset($detail)){$check_user_data=mysql_query("SELECT detail FROM $tbl_name WHERE id='$id'") or die(mysql_error());$row = mysql_fetch_array($check_user_data);$detail=strip_tags($row['detail']);$detail=stripslashes($detail);}
$check_user_data = mysql_query("SELECT * FROM forum_question WHERE id = '$id' AND topics_username = '$U'") or die(mysql_error()); if(mysql_num_rows($check_user_data) == 0){echo '<script language="javascript">alert("You must be the topic author to edit this topic.");window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';
}else{
?>
<div class='form'>
<form id="form1" name="form1" method="post" action="cms-edit-topic.php?id=<? echo stripslashes($id); ?>&username=<? echo stripslashes($U); ?>">
<table width="700" border="1" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCC">
<tr>
<td valign="top" class='mid'><b>Detail</b></td>
<td><textarea name="detail" cols="50" rows="9" id="detail" onKeyDown="textCounter(this.form.detail,this.form.remLen,10000);" onKeyUp="textCounter(this.form.detail,this.form.remLen,10000);"></textarea> 6 to 10000 characters
<br>
<input readonly type=text name=remLen size=5 maxlength=5 value="10000"> characters left
</td><input type="hidden" name="flag" value="1"><input type="hidden" name="username" value=" "><input type="hidden" name="id" value=" ">
</tr>
<tr><td><input type="submit" name="submit" value="submit"></td> <td class='mid' colspan=2><b><a href="cms-view-topic.php?username=<? echo stripslashes($U); ?>&id=<? echo stripslashes($id); ?>">Return to Topic—don't edit</a></b></td></tr>
</table>
</form>
</div>
<script language="javascript">
var c = <?php echo json_encode($detail); ?>;
if (c != null && c!=""){document.form1.detail.value=c;}
</script>
<?php
if(isset($detail)){
$detail=substr($detail,0,10000);
$detail = strip_tags($detail);
$pattern2 = '/[^a-zA-Z0-9\\s\\.\\,\\!\\;\\-\\_\\"\\?\\047\\:\\(\\)\\057]/i';
$detail=preg_replace($pattern2, "", $detail);
$detail=mysql_real_escape_string($detail);
if (strlen($detail)<6) {
echo '<script language="javascript">alert("Please enter 6 to 10000 characters for details."); window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';
}else{
$datetime=date("d/m/y H:i:s");
if($flag=="1"){
mysql_query("UPDATE $tbl_name SET detail = '$detail', datetime = '$datetime' WHERE id='$id'") or die('Error ,saving failed');
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The editing was successfully accomplished.");window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';}
else{echo '<script language="javascript">alert("Editing failed.");window.location = "cms-view-topic.php?id='.$id.'&username='.$U.'"; </script>';}
}
}
}
}
mysql_close();
?>
<script language="javascript">
var u = <?php echo json_encode($U); ?>;
u=u.replace(/\\/g,'');
document.form1.username.value=u;
var i = <?php echo json_encode($id); ?>;
i=i.replace(/\\/g,'');
document.form1.id.value=i;
</script>
<div class='info'>In Detail field, you may use single or double quotes or Enter/Return. Use Returns for new paragraphs. For italics, starting and ending tags are (i-) and (ii-). For bold, use (b-) and (bb-). Underline is (u-) and (uu-). For links, use (l-) then domain <i>without http://</i>, then (ll-) then link text, then (lll-). For emails, use (e-) then email address <i>with (ee-) instead of @</i>, then (eee-) then subject, then (eeee-) then link text, then (eeeee-). For pictures, use (p-) as start tag, then full URL path to picture, then (pp-) as end tag. If the image is wider than 580 pixels, resave it to 580.</div>
</body>
</html>