MySQL
  Home arrow MySQL arrow Creating An Online Photo Album with PHP an...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Creating An Online Photo Album with PHP and GD: Part 2
By: Frank Manno
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 22
    2003-08-29

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More MySQL Articles
    More By Frank Manno

     

    IBM® developerWorks developerWorks - FREE Tools!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Discovering the value of WebSphere Process Server

    WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies.
    FREE! Go There Now!


    NEW! Hacking 101

    Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

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







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek