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 / 21
    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!


    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! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    FREE! Go There Now!


    NEW! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Rational Talks to You:Per Kroll on Rational Method Composer Plug-in customization

    Join this Rational Talks to You teleconference on December 11 at 1:00 pm ET to get tips on building your own plugins with Rational Method Composer. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Performance Tester V7.0.1

    Get a free trial download of the latest version of IBM Rational Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Tester for SOA Quality V7.0.1

    Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services.
    FREE! Go There Now!


    NEW! Webcast: Accelerating Software Innovation with System z

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Webcast: 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!



    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-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek