Creating a News System with PHP - Part 2 - Deleting an Item
(Page 3 of 5 )
Ok, let's make the links actually do something! Let's deal with the delete link first. It is a bit less complicated than the edit link. First thing we will need to do is add a line of code that checks to see if the delete link has been clicked. We will check to see if the $action variable is set to delete with some code like this.
<?php if($action == "delete") { ?> |
Simple enough eh? Ok, now we need to check a password to make sure it is ok to delete it and at the same time we will be confirming the deletion. We are basically going to do the same thing as we would to display all the news, except we are going to use the id we passed to the delete portion of the script to only display the one news item we want to delete.
<?php if($action == "delete") { echo "<H2>You are about to delete the following news item.</H2>\n"; $data = file('news.txt'); $element = trim($data[$id]); $pieces = explode("|", $element); echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b>\n"; echo "<BR><BR>\n"; echo "Are you sure you want to delete this news item? If so, enter the password and click on Delete.<BR>\n"; echo "<FORM ACTION=\"$PHP_SELF?action=delete\" METHOD=\"POST\" NAME=\"deleteform\">\n"; echo "Password:<BR>\n"; echo "<INPUT TYPE=\"password\" SIZE=\"30\" NAME=\"password\"><BR>\n"; echo "<INPUT TYPE=\"hidden\" NAME=\"id\" VALUE=\"$id\">\n"; echo "<INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Delete\"><BR>\n"; echo "</FORM>\n"; exit; } ?> |
You'll notice that I included a hidden field that holds the id that was passed to the delete portion of the script. The reason I did this is that we will still need this id when we actually delete the news item. Now, what we need to do is add some code that checks to see if the action is set to delete AND the password field of the form has been set.
<?php if($action == "delete" && isset($HTTP_POST_VARS['password'])) { ?> |
Ok, that should suffice. That line should go to the very top of our script. Definitely make it above the last snippet that checked for an action of delete. If we don't check this first, things won't execute in the order we want them to. Now, let's check the password and then actually delete the news item.
<?php if($action == "delete" && isset($HTTP_POST_VARS['password'])) { //obviously you should change this password on the next line if($HTTP_POST_VARS['password'] == "deletepass") { $data = file('news.txt'); //this next line will remove the single news item from the array array_splice($data,$id,1); //now we open the file with mode 'w' which truncates the file $fp = fopen('news.txt','w'); foreach($data as $element) { fwrite($fp, $element); } fclose($fp); echo "Item deleted!<BR><BR>\n"; echo "<a href=\"$PHP_SELF\">Go Back</a>\n"; exit; } else { echo "Bad password!\n"; exit; } } ?> |
Next: Editing an Item >>
More Miscellaneous Articles
More By Matt Wade