#native_company# #native_desc#
#native_cta#

PHP Web Blog – Part 2

By Eric Besserer
on June 19, 2008

In Part 2 of our PHP Web Blog tutorial, we will create the administration page that will allow us to add, edit or delete the contents of our blog. If you haven’t worked through part 1, you’ll want to start by reading the first part of this article.
Security for the administration page will not be addressed directly here, but it is recommended that some form of access restriction is used. If the page is being displayed via an Apache web server, the .htaccess file can be used to restrict the folder. For additional security, the directory where this page is located does not need to be the same as the front page.
The creation of our administration page begins by reusing some of the code from the front page. This will fetch the data from the main page and begin to format it into a table for easy viewing.
Since we will be working with the data from a database, we need to have a method of tracking the different entries. We can accomplish this by using an auto incrementing field in our database. We will need to retrieve the ID field in addition to all the other fields. Since we need data from all the fields, an asterisk (*) within the query will cause mySQL to provide all the data from the table. Also added is an include that was created in the previous article which allows us to easily connect to the mySQL server.
<?
require ('/some/local/path/sql_connect.inc');

//connecting to our SQL database
sql_conenct('blog');

//This is the query for the administration; 
//we are obtaining all articles that are available with all columns.
$query = 'SELECT * FROM blog_entries ORDER BY date_entered DESC';

//This runs the query to view
//If we get a positive result in $results, it will process the while loop
If ($results = mysql_query ($query)) {

//Creates the diplay table
?>
	<table align="center" border="1" width="80%">
		<tr>

			<td colspan="2">
				<b><center>News Management</b></center></b>
			</td>
		</tr>

<?php
Now that the mySQL connection is achieved and data has been returned, it needs to be processed
into a more human-friendly format. The string manipulation commands that are used are the same
as those used on the front page. The only difference from the front page is the addition of
the ‘blog_id’ field. This is used to uniquely identify each blog entry in the database.
	While ($row = mysql_fetch_array($results)) { 
//inputs the data into the table
		$title = $row['title'];
		$user = $row['user'];
		$id = $row['blog_id'];
//The time data is being formated for a proper display to the page
        $date_entered = date ('F j g:i A', $row['date_entered']);
		$entry = nl2br ($entry);
?>
	<tr>
		<td colspan="2">
			<table align="center" border="0" width="100%">
				<tr>
					<td>

<b><?php echo $title ?></b> - Posted by: <b><?php echo $user; ?></b>
				</td>
				<td>
	<div align="right"><?php echo $date_entered; ?></div>

			</td>
			</tr>
			</table>
			</td>
	</tr>
	<tr>
		<td colspan="2"><?php echo $entry; ?></td>
		</tr>
Now that we have all the information for the blog entry displayed, options need to be
added to allow for the manipulation of the data. A new row is created with two
forms: one form will direct the admin to an ‘edit’ page, and the second form will allow the
deletion of the blog entry. The ‘ID’ gets passed as a hidden variable in the form, which is used so that the pages in question will be able to properly identify the blog entry
that needs to be edited. The table is then closed, completing our while loop.

<tr>
	<td>
               <table align="center" width="200" border="0">
        <tr>
		<td>
                <form action="edit.php" method="post">
                <input type="hidden" name="id" value="<?=$id ?>">
                <input type="submit" name="submit" value="Edit">
                </form>
			</td>
			<td>
                <form action="delete.php" method="post">
                <input type="hidden" name="id" value="<?=$id ?>">
                <input type="submit" name="submit" value="Delete">
                </form>
			</td>
					</tr>
				</table>
			</td>
		</tr>
	<?php
	}
	?>
	</table>
   <?php
} else { 
//if the query did not run.
die ("<p>Could not run query because: <b>" . mysql_error() . "</b></p>n");
}

mysql_close(); 
//Closes our SQL session
Now that the list of blog entries has been fully posted, a form needs to be created to allow
us the option of adding a new entry to the database. Four dynamic pieces of information
are gathered from the form. This page will then forward the data to a processing page that will
be created shortly. Since linking to this form is denied, POST data is used.
?>
<form action="add.php" method="POST">
<table align="center">

<tr>
<td>Entery Title: </td>
<td><input type="text" name="title" size="40" maxsize="100" /></td>
</tr>
<tr>

<td>User : </td>
<td><input type="text" name="user" size="40" maxsize="100" /></td>
</tr>
<tr>
<td>Entry Text: </td>

<td><textarea name="entry" cols="100" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Add Event" /></td>

</tr>
</table>
</form>
The front end of the administration page is now complete. The next page to be created is the first of the processing pages–the add page. This is a two stage process. First the data needs to be obtained from the POST data. Depending on Global Registers this stage may be skipped. The second stage involves cleaning up the data and formatting it into a compatible format for the mySQL database. Characters such as quotation marks and apostrophes can cause the query to fail. Escape characters will need to be added as a result. An error trap is also added here to check for post data. If it exists, it will process the page, otherwise it will display an error message.


if (isset($_POST['submit']) {
   require ('/some/local/path/sql_connect.inc');

//connecting to our SQL database
   sql_conenct('blog');
If Global Registers is enabled, this stage can be safely skipped. If you create a variable with the same name as POST/GET data, PHP will automatically fill in the variable with the post data (if Global Registers is enabled). Adding this step will not cause any problems, so I would suggest using this method as a “best practice” guideline.
   $title = $_POST['title'];
   $entry = $_POST['entry'];
   $user = $_POST['user'];
The trim command simply removes any extra blank space at the beginning or end of the strings. This is done to keep the data as small as possible and to make it look better when it is displayed.
   //Trims the values to clean up the text
   trim ($title);
   trim ($entry);
   trim ($user);
Addslashes is a function built into PHP that will add the escape character (‘/’) to any problematic characters such as quotation marks and apostrophes. Addslashes may or may not be necessary depending on whether the PHP server has magicquotes enabled. With magicquotes enabled, the PHP server will automatically add the forward slash, otherwise the addslashes function needs to be used.
   //adding in escape characters for the query
   $title = addslashes ($title);
   $entry = addslashes ($entry);
   $user = addslashes ($user);
Now that all the data has been processed, the query to add it into the SQL database is created. Since this is new data, an INSERT is used so that mySQL will create a new row for this event. Take note that if the id_blog field is set to 0, mySQL will automatically increment this for us. This way the ID stays unique.
   //define the query
   $query = "INSERT INTO blog_entries (blog_id, title, entry, date_entered, user) 
VALUES (0, '$title', '$entry', UNIX_TIMESTAMP(), '$user')";
The remainder of the page sends the query to the mySQL database. Additionally, all of the messages are created here to let the user know what has happened by adding the blog entry.
   //executes the query
   if (@mysql_query ($query)) { 
?>
     <center>The event was successfully saved. 
<a href="index.php">Return to administrative 
page</a></center>
<?php 
   } else { 
?>
     <center>The event could not be saved. 
<a href="index.php">Return to administrative 
page</a></center>
<?php 
   }
mysql_close(); //Closes our SQL session
} else {
     <center>There is no data to process. 
<a href="index.php">Return to administrative 
page</a></center>
}
Part 2 of our web blog project is now finished. We’ve discussed how to send and receive POST data, and how to format that data for entry into a database by using commands such as trim and addslashes. As a result of this data manipulation, we also covered some of the PHP options that affect how data is handled. Additionally we talked about how to insert information into the mySQL database once the strings were properly edited. Finally, we added the forms for the edit and delete portions of the administration page.
In the final part of our PHP web blog tutorial, we will discuss how to edit the existing data and remove blog entries from the database. One of the new techniques that will be covered is a method which will allow the use of “sticky” forms during the editing of blog entries. Stay tuned for the final part in our series!