PEAR CMS: Index and Delete Scripts - Delete Script continued
(Page 2 of 4 )
First, we check to see if an author_ID has been sent. Since the id will come from an untrusted source, we have to filter the ID to make sure that it is what we expect it to be; in other words, we expect a number and that is what we should get. To verify that the ID is a number, we use the tried and tested is_numeric() function. This function will evaluate to false if the id is anything but a number.
//check if author id has been sent
if(isset($_GET['aid'])){
//check if it is numeric
if(is_numeric($_GET['aid'])){
If both tests are passed, then the code continues to run a delete query that will remove the author that matches the given author ID:
//first delete author
$sql="DELETE FROM authors WHERE aid=$_GET['aid']";
$delauth = $db->query($sql);
If the query is unsuccessful, the $err variable is set to TRUE. This value will be used later to determine certain actions that the code must take. A error message is also added so that the user can see exactly where the error took place:
if(!$delauth){
$err=true
$errmsg=”Error occurred while trying to remove author”;
}
Another query is run, but this time it is to remove all the articles that are related to the just-deleted author. This query is actually very important, since the articles will be left in the database without any link to the authors table, which also means that we won't be able to delete them in the same way that the other articles can be deleted:
//Then delete all articles written by author
$sql="DELETE * FROM stories WHERE author=$_GET['aid']";
$delarts= $db->query($sql);
The result value of the query is checked to see whether or not the query was successful. If it was not successful, the $err variable will be set to TRUE. An appropriate error message will also be set at this point:
if(!$delarts){
$err=true;
$errmsg.=”Error occurred while trying to remove articles related to author ID:”.$_GET[‘aid’].”<br>”;
}
If the author ID was not sent in as a number, then the $err value is set to TRUE and the appropriate error message was set.
}else{
$err=TRUE;
$errmsg.=”Invalid ID format<br>”;
}//end numeric
If the author ID was empty or not sent, then a $errmsg is set and the $err is set to TRUE:
}else{
$err=TRUE;
$errmsg.=”Author ID not found.”<br>”;
}//end
If there are no errors, then the user is taken back to the listauthors page which should then reflect the changes:
if(!$err){
//get back to the list authors page
header(“location:listauth.php");
If there were errors, they are printed out to the screen:
}else{
echo The following error(s) occurred:<br>
echo $errmsg.”<br>”;
}
?>
That’s it for the delete script. Next we look at the index.php script.