Home arrow MySQL arrow Creating An Online Photo Album with PHP and GD: Part 2
MYSQL

Creating An Online Photo Album with PHP and GD: Part 2


In this part Frank will explain how to code the photo album using PHP and MySQL. This is the second part of his series and focuses on building the user interface.

Author Info:
By: Frank Manno
Rating: 4 stars4 stars4 stars4 stars4 stars / 28
August 29, 2003

print this article
SEARCH DEVARTICLES

In this part Frank will explain how to code the photo album using PHP and MySQL. This is the second part of his series and focuses on building the user interface.

Before we can upload our images, we need to create our albums.  Our album creation form is very simple.  We will have 2 fields and 1 button: album name, album description, and submit.  We’ll call our script create_album.php:

<?php
     include("../include/config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Add Album(s)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td><form action="add_album.php" method="post" name="">
        <p> </p>
        <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0" id="addAlbum">
          <tr>
            <td valign="top"> Add
            New Album</td>
          </tr>
        </table>
        <table width="60%" border="0" align="center" cellpadding="5" cellspacing="0">
          <tr>
            <td height="35" colspan="2">Please indicate the number of images you wish
              to upload to your album(s). If you would like to create a new album,
            click the Create New Album link below.</td>
          </tr>
          <tr>
            <td> </td>
            <td> </td>
          </tr>
          <tr>
            <td>Album Name:</td>
            <td><input name="album_name" type="text" id="album_name" size="40">
 <br>
<br><a href="edit_albums.php">Edit Existing Album(s)</a> </td>
          </tr>
          <tr>
            <td>Album Description:</td>
            <td><textarea name="album_desc" cols="30" rows="4" id="album_desc"></textarea></td>
          </tr>
          <tr>
            <td><p>             </p>
            </td>
            <td><input name="submit" type="submit" id="submit" value="Continue"></td>
          </tr>       
        </table>
        <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0">
          <tr>
            <td><a href="index.php">Main Menu</a> | <a href="new_album.php">Create
                New Album</a> | <a href="../gallery.php">View Gallery</a></td>
          </tr>
        </table>
      </form>
    </td>
  </tr>
</table>
</body>
</html>

The HTML code is straight-forward; however, I’ll explain the PHP code from above:

<?php
     include("../include/config.php");
?>

We’ll be including config.php in all of our files.  The config.php file allows us to make use of global variables throughout our application.  Our config.php file looks like this:

<?php
     // Include file for database connectivity
     $db_server = "localhost";
     $db_user = "admin";
     $db_pass = "admin";
     $db_name = "album";
     // Number of images to display per row in gallery view    
     DEFINE("IMAGE_DISPLAY", 3);
     /*****
      * Connects to database system
      */
     function db_connect(){
         global $db_server;
         global $db_user;
         global $db_pass;
         global $db_name;
         $dbcnx = mysql_connect($db_server, $db_user, $db_pass) or die("Error connecting to database: " . mysql_error());
         $dbsel = mysql_select_db($db_name, $dbcnx) or die("Error reading from database table: " . mysql_error());
     }
  /*****
   * Displays HTML output page.  The message argument, if passed,
   * will be displayed to the user.  The title element, is passed,                   
   * replaces the page title, and the cell Boolean places the page
   * $msg between <td></td>
   */ 
   function displayPage($msg = "", $title="", $cell = true){
?>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
 <head>
 <title><?php echo($title); ?></title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 </head>
 <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
 <table width="100%" border="0" cellpadding="0" cellspacing="0">
   <tr>
  <td>
   <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0">
     <tr>
    <td width="40%" valign="top"><h1><?php echo($title); ?></h1></td>
     </tr>
   </table>
   <table width="60%" border="0" align="center" cellpadding="5" cellspacing="0">
   <tr>
    <?php
     // Display opening <td> tag
     if ($cell)
      echo("<td>");
     echo($msg);
     
     // Display closing <td> tag
     if ($cell)
      echo("</td>");   
    ?>
   </tr>
   </table>
  </td>
   </tr>
 </table>
 </body>
<?php
  }      
?>

Our config file initializes our connection variables: $db_server, $db_user, $db_pass, and $db_name.  These variables are used in the db_connect() function which simply connects to our database system (in this case MySQL) and selects the album database we’ll be using in our application.

Our create_album.php file is simply a form that accepts user-input, and submits the data to our processing script.  Once the data is entered by the user, our processor script checks to see if all the fields have been completed; if not, an error message is displayed.  If all fields are complete, the album data is added to the database.  We’ll call our processor script add_album.php:

<?php
      include_once("../include/config.php");
      // Verify that all form elements are completed
      if (empty($_POST['album_name']) || empty($_POST['album_desc'])){
   displayPage("Please complete all required fields!<br /><a href='new_album.php'>Go Back</a>", "Error Adding Album!");
         die();
      } 
      // Connect to database
      db_connect();    
      $sql = "INSERT INTO albums VALUES(0, '" . addslashes($_POST['album_name']) . "', '" . addslashes($_POST['album_desc']) . "', 0, '', '')";
      $result = @mysql_query($sql) or die("Error inserting record: " . mysql_error());
      if ($result){
      // Notify use that album was successfully created.
   $msg .= "Album <strong>" . $_POST['album_name'] . "</strong> successfully created!";
   $msg .= "<br /><a href='edit_album.php?album_id=" . mysql_insert_id() . "'>Click here</a> to administrate the " . $_POST['album_name'] . " album";
   $msg .= "<p><a href='index.php'>Click here</a> to return to the administrative area</p>";
   displayPage($msg, "Album " . $_POST['album_name'] . "Added!");
      }
?>

Here’s a breakdown of the code:

      include_once("../include/config.php");  
      // Verify that all form elements are completed
      if (empty($_POST['album_name']) || empty($_POST['album_desc'])){
   displayPage("Please complete all required fields!<br /><a href='new_album.php'>Go Back</a>", "Error Adding Album!");
         die();
      }

The include line, again, is to make use of the global variables and function that allow us to connect to the database.

The first thing we do is check to see if the album name and description is incomplete (empty).  If they are empty, we call the displayPage() function and pass to it our error message.  The displayPage() function simply accepts a string argument, and displays the message to the user.  Once the displayPage() function has been called, we call the die() function, which simply terminates the script’s execution.

If the album name and description has been completed, we connect to our database by calling the db_connect() function, located in our config.php script.

      // Connect to database
      db_connect();     
      $sql = "INSERT INTO albums VALUES(0, '" . addslashes($_POST['album_name']) . "', '" . addslashes($_POST['album_desc']) . "', '')";
      $result = @mysql_query($sql) or die("Error inserting record: " . mysql_error());
     

Once connected, we create and execute our SQL statement, which simply inserts the values passed from the form into our album table.  We deliberately leave the value of the thumbnail location empty; this value will be populated when uploading our album images.

      if ($result){
      // Notify use that album was successfully created.
   $msg .= "Album <strong>" . $_POST['album_name'] . "</strong> successfully created!";
   $msg .= "<br /><a href='edit_album.php?album_id=" . mysql_insert_id() . "'>Click here</a> to administrate the " . $_POST['album_name'] . " album";
   $msg .= "<p><a href='index.php'>Click here</a> to return to the administrative area</p>";
   displayPage($msg);

If our insert query is successfully executed, we call the displayPage() function, and pass it our string argument; in this case, a notice to the user that the album has been added.  We also indicate options for administrating the album (ie: adding pictures, etc.).

Now that our add_album.php script is complete, we can add functionality to edit our existing albums.  We’ll create a script called edit_albums.php:

<?php
 include_once("../include/config.php");
 // Has album been updated?
 if ( $_POST['edit'] ){
  if ( empty($_POST['album_name']) || empty($_POST['album_desc'])){
   $msg = "Please complete all required fields!<br /><a href='new_album.php'>Go Back</a>";
   displayPage( $msg, "Error Updating Album!");
   die();
  }
  db_connect(); 
  // Insert updated record into DB
  $sql = "UPDATE albums SET album_name = '" . addslashes($_POST['album_name']) . "', album_desc = '" . addslashes($_POST['album_desc']) . "' WHERE album_id = " . addslashes($_POST['album_id']);
  $result = @mysql_query( $sql ) or die("Error inserting record: " . mysql_error());
  if ($result){
   $msg = "Album updated successfully!<br /><a href='index.php'>Return to Admin Menu</a>";
   displayPage($msg, "Album Updated Successfully!");
   die();
  }
 } else if ( !$_POST['edit'] && !empty($_GET['album_id'])){
  db_connect();
  // Retrieve album information
  $sql = "SELECT album_id, album_name, album_desc FROM albums WHERE album_id = " . addslahes($_GET['album_id']);
  $result = @mysql_query( $sql ) or die("Error retrieving record: " . mysql_error());
  while($row = mysql_fetch_array( $result )){
   // Display edit page
   $msg .= "<form action=\"edit_albums.php\" method=\"post\">\n";
   $msg .= "<table width=\"60%\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n";
   $msg .= "<tr>\n<td>Album Name:</td>\n<td><input name=\"album_name\" type=\"text\" id=\"album_name\" size=\"40\" value=\"" . $row['album_name'] . "\"></td>\n</tr>\n";
   $msg .= "<tr>\n<td>Album Description:</td>\n<td><textarea name=\"album_desc\" cols=\"30\" rows=\"4\" id=\"album_desc\">" . $row['album_desc'] . "</textarea></td>\n</tr>\n";
   $msg .= "<tr>\n<td><input type=\"hidden\" name=\"edit\" value=\"1\"><input type=\"hidden\" name=\"album_id\" value=\"" . $_GET['album_id'] . "\"></td>\n";
   $msg .= "<td><input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Continue\">";
   $msg .= "<a href=\"del_albums.php?album_id=" . addslashes($_GET['album_id']) . "\">Delete</a>";
   $msg .= "</td>\n</tr>\n</table>\n</form>";
   $album_name = $row['album_name'];
  }
  displayPage($msg, "Editing Album " . $album_name . ":");
 // Display album summaries
 } elseif ( !$_GET['album_id'] ){
  db_connect();
  // Retrieve all album information  
  $sql = "SELECT album_id, album_name FROM albums";
  $result = @mysql_query( $sql ) or die( "Error retrieving records: " . mysql_error() );
  $i = 0;
  while($row = mysql_fetch_array($result)){    
   if (( $i % 2 ) == 0 && ( $i != 0 )){
    $msg .= ("</tr>\n<tr>");
   }
   $msg .= ("<td>" . ($i + 1) . ". <a href='edit_albums.php?album_id=" . $row['album_id'] . "'>" . $row['album_name'] . "</td>\n");   
   $i++;
  }
  displayPage( $msg, "Edit Albums", false );
 }   
?>

Here’s a breakdown of the code:

 include_once("../include/config.php");
 // Has album been updated?
 if ( $_POST['edit'] ){
  if ( empty($_POST['album_name']) || empty($_POST['album_desc'])){
   $msg = "Please complete all required fields!<br /><a href='new_album.php'>Go Back</a>";
   displayPage( $msg, "Error Updating Album!");
   die();
  }
  db_connect(); 
  // Insert updated record into DB
  $sql = "UPDATE albums SET album_name = '" . addslashes($_POST['album_name']) . "', album_desc = '" . addslashes($_POST['album_desc']) . "' WHERE album_id = " . addslashes($_POST['album_id']);
  $result = @mysql_query( $sql ) or die("Error inserting record: " . mysql_error());
  if ($result){
   $msg = "Album updated successfully!<br /><a href='index.php'>Return to Admin Menu</a>";
   displayPage($msg, "Album Updated Successfully!");
   die();
  }

First we test to see if the hidden variable “edit” has been set.  This variable is set ONLY after an album has been edited.  It may seem like we’re working backwards, and that’s what we’re doing.  We’re checking to see if the album has been edited, then we check whether a specific album ID has been chosen.  If neither of the two conditions is true, we display all albums in the database with a link to edit each.

If the edit value has been set – in other words, we’ve edited our album details -- we test to ensure that each field has been completed.  If not, we display an error message to the user, with an option to return back to the edit screen.  If the fields have been completed, we connect to the database, and update the specific album.  We then display a result page notifying that the album has been successfully updated:

 } else if ( !$_POST['edit'] && !empty($_GET['album_id'])){ 
  db_connect();
  // Retrieve album information
  $sql = "SELECT album_id, album_name, album_desc FROM albums WHERE album_id = " . addslahes($_GET['album_id']);
  $result = @mysql_query( $sql ) or die("Error retrieving record: " . mysql_error());
  while($row = mysql_fetch_array( $result )){
   // Display edit page
   $msg .= "<form action=\"edit_albums.php\" method=\"post\">\n";
   $msg .= "<table width=\"60%\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n";
   $msg .= "<tr>\n<td>Album Name:</td>\n<td><input name=\"album_name\" type=\"text\" id=\"album_name\" size=\"40\" value=\"" . $row['album_name'] . "\"></td>\n</tr>\n";
   $msg .= "<tr>\n<td>Album Description:</td>\n<td><textarea name=\"album_desc\" cols=\"30\" rows=\"4\" id=\"album_desc\">" . $row['album_desc'] . "</textarea></td>\n</tr>\n";
   $msg .= "<tr>\n<td><input type=\"hidden\" name=\"edit\" value=\"1\"><input type=\"hidden\" name=\"album_id\" value=\"" . $_GET['album_id'] . "\"></td>\n";
   $msg .= "<td><input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Continue\">";
   $msg .= "<a href=\"del_albums.php?album_id=" . addslashes($_GET['album_id']) . "\">Delete</a>";
   $msg .= "</td>\n</tr>\n</table>\n</form>";
   $album_name = $row['album_name'];
  }
  displayPage($msg, "Editing Album " . $album_name . ":");
      
  
Here we test to see if edit has NOT been set and whether an album ID HAS been passed (set) through the URL query string (ie: edit_albums.php?album_id=1).  If the condition is met (true), we display our edit album form, which is simply a table containing pre-filled fields.  The value of each field is retrieved from our database, via our SQL SELECT query:

<td><input type=\"hidden\" name=\"edit\" value=\"1\"><input type=\"hidden\" name=\"album_id\" value=\"" . $_GET['album_id'] . "\">

This is where our hidden fields reside.  The first field is our edit variable that has been tested above.  The second holds the ID value of the current album we are editing.  These hidden fields are passed to the processing page as POST variables once the form is submitted.

The last link we provide is a delete link, which allows us to delete the current album we are editing.  Here, we call the del_album.php script, and pass to it our album’s ID.

 // Display album summaries
 } elseif ( !$_GET['album_id'] ){
  db_connect();
  // Retrieve all album information  
  $sql = "SELECT album_id, album_name FROM albums";
  $result = @mysql_query( $sql ) or die( "Error retrieving records: " . mysql_error() );
  $i = 0;
  while($row = mysql_fetch_array($result)){    
   if (( $i % 2 ) == 0 && ( $i != 0 )){
    $msg .= ("</tr>\n<tr>");
   }
   $msg .= ("<td>" . ($i + 1) . ". <a href='edit_albums.php?album_id=" . $row['album_id'] . "'>" . $row['album_name'] . "</td>\n");   
   $i++;
  }
  displayPage( $msg, "Edit Albums", false );
 }
  

This last test checks to see whether or not an album ID has been set.  If not, we display each album name, in the database, in an HTML table and give the option of editing the album via a hyperlink:

Now that we’ve completed the option of adding and editing our albums, its time to go ahead to add some pictures!

Our del_albums.php script is quite simple:

<?php
 include_once("../include/config.php");
 // No album id has been selected
 if( !$_GET['album_id'] ){
  // Display error message to user
  $msg .= "Album not selected.  Please choose an album you wish to delete!";
  $msg .= "<br /><a href=\"edit_album.php\">Edit albums</a>";
  displayPage($msg, "Error Selecting Album");
 } else {
  db_connect();
  // Delete specified album
  $sql = "DELETE FROM albums WHERE album_id = " . addslashes($_GET['album_id']);
  $result = @mysql_query($sql) or die("Error deleting record: " . mysql_error());
  // Display success to user
  $msg .= "Album has been successfully deleted!<br /><a href='index.php'>Return to Admin Menu</a>";
  displayPage($msg, "Album Deleted!");
 }
?>

The del_albums.php script is simply checks to see that an album ID was passed to it.  If not, an error message is displayed to the user.  If an album ID has been passed, we create an SQL DELETE statement that removes the specified album from the database.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

All MySQL Tutorials
More By Frank Manno


blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 – More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials