Part 10: Deleting entries

Originally posted by Valerie.

Please note: The Build-A-Blog series is an introduction to creating a simple blog script using PHP. These tutorials are meant to help you to learn PHP and MySQL and to use these to fetch and store data and display it on a web page. These tutorials should not be used ‘as is’ on a production website – especially if you are new to PHP and do not understand what you are doing. We would recommend that you try the B-A-B series on a safe, development environment – such as an offline installation of PHP and MySQL – so you can learn how everything works.

GWG and its staffers accept no responsibility for anything that may (or may not) happen to your site or server as a result of you using these tutorials – you do so AT YOUR OWN RISK.

My turn! Okay, this is my attempt at writing my first tutorial.

A lot of people have been asking how to delete the entries out of build-a-blog. So that is what this tutorial will cover. You should have followed all of the parts of the tutorial so far up to this point, this tutorial will assume that you have.

Let’s open our update.php, or whatever file you are using to change entries after they’ve been posted.

Since we’ve already got the rest of the code for this file, let’s find the part that looks something like this, towards the end of your file:

<p><input type="submit" name="update" id="update" value="Update" /></p>

</form>

Optional: right after that, let’s put a little warning message…

<p><strong>Before deleting, be absolutely sure - there is no confirmation nor is there any way to reverse deletion!</strong><br />
<small>(You may be shown your entry again after deleting - do not worry, it HAS been deleted.  Check the main page of the blog if you are still unsure.</small></p>

This is just a little note to remind you that once you will click the button, your entry will be gone. There will be no confirmation, no box asking you "are you sure?" That can be written in later.

Now we’ve got to write the actual code to delete the entry.
This is a new form, and like the update form, it will use the same page to process what you want it to do.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

We need to pass the variable of the id (if you remember, the id is passed to the update form from the list of entries you clicked on to get there, so we’ll need to do the same thing here):

<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />

And we want to submit our decision, aka delete it.

<input type="submit" name="delete" id="delete" value="Yes, I am absolutely and positively sure I want to delete this entry." />

</form>

Of course, your button can say whatever you want it to, just change the part for the value – just don’t use apostrophes or quotes.

Now, to process the deletion.
Let’s skip over the part from the original update form that starts as follows:

    if (isset($_POST['update'])) {

And closes like so:

    header("Location: journal.php?id=" . $id);

}

After that, skip a line and start your process. Notice that we gave our above submit button a name of "delete" this is where that comes into play.

if (isset($_POST['delete'])) {

Let’s get the id from the form:

    $id = (int)$_POST['id'];

Next, what should PHP do with the it?

    $result = mysql_query("DELETE FROM php_blog WHERE id='$id'") or print ("Can't delete entry.<br />" . mysql_error());

The above will also give you the output of an error if deletion is unsuccessful for any reason.

Now what do we do if deletion is successful? If the result of deletion is != (not equal to) false, then we say so. We’re also telling the code to "exit" here – without this, an error would occur after deletion. You can include a link back to your main admin page here if you like.

    if ($result != false) {
        print "The entry has been successfully deleted from the database.";
        exit;
    }
}

The end!

Okay, just kidding, let’s wrap it up. What does it look like now?
You should have two parts: part 1 is after the update form, before processing that form, and will contain your delete form; part 2 is after processing the update and it will process the delete form.

Your complete update.php should look more or less like this:

<?php
mysql_connect ('localhost', 'db_username', 'db_password') ;
mysql_select_db ('db_name');

if (isset($_POST['update'])) {

    $id = htmlspecialchars(strip_tags($_POST['id']));
    $month = htmlspecialchars(strip_tags($_POST['month']));
    $date = htmlspecialchars(strip_tags($_POST['date']));
    $year = htmlspecialchars(strip_tags($_POST['year']));
    $time = htmlspecialchars(strip_tags($_POST['time']));
    $entry = $_POST['entry'];
    $title = htmlspecialchars(strip_tags($_POST['title']));
    if (isset($_POST['password'])) $password = htmlspecialchars(strip_tags($_POST['password']));
    else $password = "";

    $entry = nl2br($entry);

    if (!get_magic_quotes_gpc()) {
        $title = addslashes($title);
        $entry = addslashes($entry);
    }

    $timestamp = strtotime ($month . " " . $date . " " . $year . " " . $time);

    $result = mysql_query("UPDATE php_blog SET timestamp='$timestamp', title='$title', entry='$entry', password='$password' WHERE id='$id' LIMIT 1") or print ("Can't update entry.<br />" . mysql_error());

    header("Location: journal.php?id=" . $id);

}

if (isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    $result = mysql_query("DELETE FROM php_blog WHERE id='$id'") or print ("Can't delete entry.<br />" . mysql_error());
    if ($result != false) {
        print "The entry has been successfully deleted from the database.";
        exit;
    }
}

if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid entry ID.");
}
else {
    $id = (int)$_GET['id'];
}

$result = mysql_query ("SELECT * FROM php_blog WHERE id='$id'") or print ("Can't select entry.<br />" . $sql . "<br />" . mysql_error());

while ($row = mysql_fetch_array($result)) {
    $old_timestamp = $row['timestamp'];
    $old_title = stripslashes($row['title']);
    $old_entry = stripslashes($row['entry']);
    $old_password = $row['password'];

    $old_title = str_replace('"','\'',$old_title);
    $old_entry = str_replace('<br />', '', $old_entry);

    $old_month = date("F",$old_timestamp);
    $old_date = date("d",$old_timestamp);
    $old_year = date("Y",$old_timestamp);
    $old_time = date("H:i",$old_timestamp);
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<p><input type="hidden" name="id" value="<?php echo $id; ?>" />

<strong><label for="month">Date (month, day, year):</label></strong> 

<select name="month" id="month">
<option value="<?php echo $old_month; ?>"><?php echo $old_month; ?></option>

<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>

<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>

<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>

</select>

<input type="text" name="date" id="date" size="2" value="<?php echo $old_date; ?>" />

<select name="year" id="year">
<option value="<?php echo $old_year; ?>"><?php echo $old_year; ?></option>
<option value="2004">2004</option>

<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>

<option value="2009">2009</option>
<option value="2010">2010</option>
</select>

<strong><label for="time">Time:</label></strong> <input type="text" name="time" id="time" size="5" value="<?php echo $old_time; ?>" /></p>

<p><strong><label for="title">Title:</label></strong> <input type="text" name="title" id="title" value="<?php echo $old_title; ?>" size="40" /> </p>

<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1"<?php if($old_password == 1) echo " checked=\"checked\""; ?> /></p>

<p><textarea cols="80" rows="20" name="entry" id="entry"><?php echo $old_entry; ?></textarea></p>

<p><input type="submit" name="update" id="update" value="Update"></p>

</form>

<p><strong>Before deleting, be absolutely sure - there is no confirmation nor is there any way to reverse deletion!</strong><br />
<small>(You may be shown your entry again after deleting - do not worry, it HAS been deleted.  Check the main page of the blog if you are still unsure.</small></p>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />
<input type="submit" name="delete" id="delete" value="Yes, I am absolutely and positively sure I want to delete this entry." />

</form>

<?php

mysql_close();
?>

Now we should be all done. ;-)