PHP Code for Edit Categories in Blog Database
Content Management System: Blogs
- regular blog: home page
- small blog: home page
- tiny blog: home page
- blog: search
- blog: login
- blog: topic and replies viewing page
- blog: add topic to database
- blog: add reply to database
- blog: edit topic in database
- blog: create topic in database
- blog: delete topic in database
- blog: delete reply in database
- blog: create categories in database
- blog: edit categories in database
- blog: open or close topic
- blog: delete user account in members table
The blog's category editing page whose code is on this web page does more than you'd think it needs to at first blush. Its only goal is to let you edit categories however you want, but this involves three tables of the MySQL db, blog_answer (the replies table), blog_question (the topics table), and blogcategories which is where the category list is stored.
The editing page has several features. It allows the administrator to add a category, after which it does input validation and adds the new category to the blogcategories table. If your username does not match the administrator's username, you're sent to the login script. The validation includes strip_tags(), preg_replace(), and mysql_real_escape_string(). The replace function dumps anything but alphanumerics and underscore in the new category name, then the script saves it. When adding a category, you get a dropdown list of existing categories to peruse to make sure you don't add something already there.
Another feature is the category deletion function. It asks you Delete Which Category and again you get a dropdown list of existing categories to peruse, but this time to make sure you know the choices. When you're deleting a category, there is a couple of radio buttons that allow you to choose to either "replace category with selected one" or "delete category and its topics". Lower down in the form, you see Category to Delete and next to it you get a dropdown list of existing categories to peruse. If you are deleting OR replacing a category you must select which one in this dropdown list. Lower yet, you see Category to Replace It With (IF you are replacing it—if not, this will be ignored) and again you get a dropdown list of existing categories to peruse. Select one only if you will be replacing.
On to the PHP code. As usual, we start with config.php, since without it, the MySQL-based blog 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 the administrator's username. Note that the various pages on our blog 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 username checked to ensure it is the administrator's 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 blog app scripts have this same (almost) username checker at the top of the PHP section—except for the login script. We say "almost" because most pages (like this one) only allow the administrator access because most pages are about adding, deleting, or editing topics, replies, or categories. So, seeing if the username is the administrator's is in the user checker on most of these blog app pages.
The administrator's username is a bit silly, as you see. Feel free to change it (to AfDqC_1f3_DkI3j5k9N_ for example) when you register the administrator username and password, but you must use search and replace on ALL blog app pages searching for our silly name and replacing it with your not-as-silly name or you'll have more problems than a pregnant nun.
If your username matches the administrator's username, any category inputting is checked and sanitized, then if the script sees that you intend to delete rather than replace, due to a POSTed flag from the HTML form you just submitted, it reads through the topics table and pushes any topic record ids with your selected category into a PHP array $ids[]. Next it loops through the replies table and every record with a question_id matching any of the values in the $ids[] array is deleted. Essentially, any reply related to a topic whose category is being deleted gets dumped from the db. Then the topics table is searched for any topic with the doomed category and deletes it. Finally, the doomed category is dumped from the blogcategories table. You get informed of the success or failure of your operation.
If the script sees that you intend to replace rather than delete, due to a POSTed flag from the HTML form you just submitted, the topics table is UPDATEd and any topic with the doomed category gets its category replaced with the replacement category you selected in the dropdown list as a replacement. The category is then dumped from the blogcategories table. You get informed of the success or failure of your operation.
Next, the category adding form is echoed to the screen. Then the blogcategories table is consulted, and the categories are pushed into PHP array $cat[] for use in the form. Then the category deleting form is echoed to the screen. The select tags for each dropdown list are echoed to the screen, and then, using the $cat[] array, categories get looped in as option values to select three separate times, although the first time is for only perusal, not input. The action for the form is this same page.
If you are adding a category, the blogcategories table is checked and you're told if it already exists. If it is a new category, a PHP else statement sends you to INSERT it INTO the table. You get informed of the success or failure of your operation.
SAVE THIS PAGE AS: cms-blog-edit-category.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>Editing Blog Categories—Content Management System (CMS)</TITLE>
<meta name="description" content="Editing Blog Categories—Content Management System (CMS)">
<meta name="keywords" content="Add Category,Delete Category,Editing Blog Categories,blog,Content Management System,Content Management System Articles,php,CMS,javascript, dhtml, DHTML">
<script language="javascript">
var cat=new Array();
mactest=(navigator.userAgent.indexOf("Mac")!=-1) //My browser sniffers
is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1
Netscape=(navigator.appName.indexOf("Netscape") != -1)
msafari=(navigator.userAgent.indexOf("Safari")!= -1)
wsafari=0; if(!mactest&&msafari){wsafari=1;msafari=0}
is_opera = 0; if(window.opera){is_opera=1}
is_ie_mac = 0; is_ie=0;if(document.all){is_ie=1}
if(is_ie&&mactest){is_ie_mac=1}
function fix(){if(Netscape||is_opera){e=document.getElementById('top');e.style.marginTop='1px';e=document.getElementById('info');e.style.marginTop='1px';}}
</script>
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-color:#ddd}
p, li {font:13px Verdana; color:black;text-align:left}
h1 {font:bold 20px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
h3 {font:bold 11px Verdana;}
.url {position:absolute;top:0px;left:10px;width:989px}
.form {position:absolute;top:140px;left:200px;width:700px}
.form3 {position:absolute;top:160px;left:600px;width:390px}
.form2 {position:absolute;top:240px;left:200px;width:450px}
.info {position:absolute;top:80px;left:200px;width:600px;border:1px solid blue;padding:6px;background-color:#bbb}
.side {position:absolute;top:160px;left:715px;width:277px;padding:6px;background-color:#bbb;border:1px solid blue}
</style>
</head>
<body onload='fix()'>
<?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)){if($U<>"DIRTY_dog_DROPPINGS_"){unset($U);}}else{unset($U);}
if (!isset($U)){echo '<script language="javascript">alert("You are not the Administrator. Go login again but you can only add replies or just read topics.");window.location="blog-login.php"; </script>';}
$pattern1 = '/[^a-zA-Z0-9\\_]/i';
$replacement = '';
$C=$_POST['category'];
$C=strip_tags($C);
$C=preg_replace($pattern1, $replacement, $C);
$C=mysql_real_escape_string($C);
$D=$_POST['del'];
$R=$_POST['repl'];
$RD=$_POST['replace_delete'];
if (strlen($D)>0 && $RD=="delete_category"){
$ids=array();
$res=mysql_query("SELECT id FROM blog_question WHERE category='$D'") or die(mysql_error());
while ($row = mysql_fetch_row($res)) {
array_push ($ids, $row[0]);}
$num_cat_in_table=mysql_num_rows($res);
for ($i=0;$i<$num_cat_in_table;$i++) {
mysql_query("DELETE FROM blog_answer WHERE question_id ='$ids[$i]'") or die('Error ,deleting failed');}
mysql_query("DELETE FROM blog_question WHERE category='$D'") or die('Error ,deleting failed');
mysql_query("DELETE FROM blogcategories WHERE category='$D'") or die('Error, deleting failed');
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The deleting was successful.");</script>';}
else{echo '<script language="javascript">alert("The deleting was unsuccessful.");</script>';}
}
if (strlen($D)>0 && $RD=="replace_category"){
mysql_query("UPDATE blog_question SET category='$R' WHERE category='$D'") or die('Error ,replacing failed');
mysql_query("DELETE FROM blogcategories WHERE category='$D'") or die('Error, deleting failed');
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The deleting was successful.");</script>';}
else{echo '<script language="javascript">alert("The deleting was unsuccessful.");</script>';}
}
echo "<div id='form' class='form'>
<form name='myform' method='post' action='cms-blog-edit-category.php?username=".stripslashes($U)."'>
<table width='450' border='0' cellpadding='2' cellspacing='2' align='left'><BR>
<tr><td width='260'><b>Add This New Category:</b></td></tr>
<tr><td><input name='category' type='text' size='29'></input></td></tr>
<tr><td><input name='save' type='submit' value='Save Category to DB'>
<input name='reset' type='reset' value='Reset'></td></tr>
</table>
</form>
</div>";
$cat=array();
$res = mysql_query("SELECT category FROM blogcategories order by category") or die(mysql_error());
while ($row = mysql_fetch_row($res)) {
array_push ($cat, $row[0]);
}
$num_cats_in_table=mysql_num_rows($res);
echo "<div class='form2'><form name='myform2' method='post' action=' '><table width='450' border='0' cellpadding='2' cellspacing='2' align='center'><tr><td width='130'>Existing categories</td><td><select name='cy'>";
for ($i=0;$i<$num_cats_in_table;$i++) {
echo "<option value='".$cat[$i]."'>".$cat[$i]."</option>";}
echo "</select></td></tr></table></form></div>";
echo "<div class='form3'><b>Delete Which Category:</b><BR><form name='myform3' method='post' action='cms-blog-edit-category.php?username=".stripslashes($U)."'><table width='390' border='0' cellpadding='2' cellspacing='2' align='center'><tr><td>
<b>Options:</b></td></tr><tr><td>
<input type='radio' name='replace_delete' value='replace_category' checked> <b>replace category with selected one</b></td></tr><tr><td>
<input type='radio' name='replace_delete' value='delete_category'> <b>delete category and its topics</b><br></td></tr><tr><td><BR><BR>Category to Delete</td><td><BR><BR><select name='del'>";
for ($i=0;$i<$num_cats_in_table;$i++) {
echo "<option value='".$cat[$i]."'>".$cat[$i]."</option>";}
echo "</select></td></tr></table><BR>";
echo "<table width='390' border='0' cellpadding='2' cellspacing='2' align='center'><tr><td>Category to Replace It With (IF you are replacing it—if not, this will be ignored)</td><td><select name='repl'>";
for ($i=0;$i<$num_cats_in_table;$i++) {
echo "<option value='".$cat[$i]."'>".$cat[$i]."</option>";}
echo "</select></td></tr></table>";
echo "<table><tr><td><input name='submit' type='submit' value='Delete Category in DB'></td></tr></table></form></div>";
if (strlen($C)>0){
$check_user_data = mysql_query("SELECT category FROM blogcategories WHERE category='$C'") or die(mysql_error());
if(mysql_num_rows($check_user_data) >0)
{echo '<script language="javascript">alert("This category exists. Please try again.")</script>;';
}else{
mysql_query("INSERT INTO blogcategories (id, category)
VALUES ('','".$C."')") or die('Error ,saving failed');
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The saving was successfully accomplished.");window.location = "cms-blog-edit-category.php?username='.$U.'";</script>';}
else{echo '<script language="javascript">alert("The saving was unsuccessful.");</script>';}
}}
mysql_close();
?>
<div id='top' class='url'>
<h1>Editing Blog Categories—Content Management System (CMS)</h1>
<div id='info' class='info'><h3>Use letters, numbers, and underscores only in categories. Categories must be under 30 characters long. <a href="cms-blog.php?username=<? echo stripslashes($U); ?>"><B>Return to Blog</B></a></h3></div>
</div>
</body>
</html>