Part 6: Creating a form to edit entries

Originally posted by Michelle.

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.

I know the next instalment on my list is comments, but someone requested a form for editing entries. That’s important, so I’ll do comments next.

What we’re going to do here is call an entry from our database, use it to fill in a form much like our submit form, and then have the submit button update that entry.

The page we’re about to create will be called update.php. You should put this page, and your entry form, in a separate password protected directory. (You can protect a directory either in your control panel, or by using .htaccess.)

Also, you won’t be able to directly access this form at http://yourdomain.com/dir/update.php — you’ll need to go to http://yoursite/dir/update.php?id=xx where xx is the id number of the entry you want to edit. Don’t worry, we’ll also create a list of entries for your admin section that will allow you to click and edit any entry.

Now, open php:

<?php

And connect to your database (remember to change the values as applicable):

mysql_connect ('localhost', 'db_username', 'db_password') ;
mysql_select_db ('db_name');

Get the ID of the entry we want to edit:

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

Now, select everything from table php_blog where id=$id:

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

In our while loop, we’re going to name all of our variables "$old_xxx" to distinguish them from the new values:

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);
}
?>

Take note of this line:

    $old_title = str_replace('"','\'',$old_title);

Having a double quote (") in our title messes with the form and can ruin our title. So we’re replacing any double quote with a single.

This line:

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

Gets rid of the HTML <br />s so we can read our entry more easily. Don’t worry, they will be added back automatically.

Create a form that is almost identical to our post form, except that all of the fields are filled in with our "old" values. Also, a hidden field to pass on the id variable, and the submit button is now called "update."

<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>

<?php

Now we process the results of the form. THIS NEEDS TO GO BELOW YOUR MySQL CONNECTION INFO, BUT ABOVE EVERYTHING ELSE WE HAVE DONE SO FAR!

If Update is pressed:

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

Clean out nasty code from our form, and check whether we’ve enabled password protection:

    $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 = "";

Add <br /> tags wherever we have a line break:

    $entry = nl2br($entry);

Escape quotes if the server doesn’t do it automatically:

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

Create our timestamp:

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

And update our table where id=$id:

    $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());

Then refresh the page so we can see our changes, and close the if statement:

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

}

Close mysql (add to the bottom of the page now!):

mysql_close();

Close PHP:

?>

And here’s our update.php page:

<?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($_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>

<?php

mysql_close();
?>