MySQL
  Home arrow MySQL arrow Creating An Online Photo Album with PHP an...
IBM Rational Software Development Conference
Iron Speed
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  
Dedicated Servers  
Download TestComplete 
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 3
By: Frank Manno
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 13
    2003-09-03

    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
     
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Part 3 is here! It is time to learn how to create an upload area as well as developing the php code so that the details about the photo are updatable.We need to determine what our requirements for the upload section will be. I’ve decided that I would first like to indicate the number of images to upload. Next, we select the album we’d like to upload our images to, and proceed on. An added option that we’ll add to the image uploads is a checkbox that will allow us to specify which photo we’d like to be the album cover for our selected album. 

    I would also like the option of not only providing a description for the albums, but also for each individual photo. Descriptions can contain EXIF information (Exchangeable Image File Format), photo date, and anything of value.

    EXIF stands for Exchangeable Image File Format, and is a standard for storing interchange information in image files, especially those using JPEG compression. Most digital cameras now use the EXIF format. – EXIF.org

    Our first form will be very simple. One field, which will indicate the number of images we would like to upload, and the other, a drop-down, to select the album to which the images will belong. We’ll call this page upload_images.php:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>Gallery - Upload Images</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" cellspacing="0" cellpadding="0">
    <tr>
    <td><form action="image_upload.php" method="post">
    <p> </p>
    <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0">
    <tr>
    <td><h1>Image Upload Area</h1></td>
    </tr>
    </table>
    <table width="60%" border="0" align="center" cellpadding="5" cellspacing="0">
    <tr>
    <td colspan="2"><p>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.</p>
    </td>
    </tr>
    <tr>
    <td> </td>
    <td> </td>
    </tr>
    <tr>
    <td>Number of Images:<br>
    (JPEG / PNG)</td>
    <td><input name="num_images" type="text" id="num_images" size="10">
    </td>
    </tr>
    <tr>
    <td>Photo Album:</td>
    <td><select name="albums" id="albums">
    <?php
    include("../include/config.php");
    db_connect();
    $sql = "SELECT album_id, album_name FROM albums";
    $result = @mysql_query( $sql ) or die("Error retrieving records: " . mysql_error());
    while ( $row = mysql_fetch_array($result) ){
    echo("<option value=" . $row['album_id'] . ">" . $row['album_name'] . "</option>");
    }
    ?>
    </select>
    </td>
    </tr>
    <tr>
    <td> </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 PHP code for our form is quite simple:

    db_connect();
    $sql = "SELECT album_id, album_name FROM albums";
    $result = @mysql_query( $sql ) or die("Error retrieving records: " . mysql_error());
    while ( $row = mysql_fetch_array($result) ){
    echo("<option value=’" . $row['album_id'] . "’>" . $row['album_name'] . "</option>\n");
    }


    We connect to our database, retrieve the album name and ID, and display the values in a drop-down form. The album ID is the value of each option, and the album name is the text that is displayed in the drop-down menu:


    Once we indicate the number of photos we’d like to upload, our upload form is displayed. Our image upload form will contain the following fields: a field to store the filename (chosen by the browse button), an image title field, and image description field, and a radio button indicating whether or not the photo is the album cover. We’ll call this page image_upload.php:

    <?php
    if (!$_POST['num_images']){
    echo("Please specify the # of images you wish to upload!<br />");
    echo("Click <a href='javascript:history.go(-1)'>here</a> to go back.");
    die();
    } else { 
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>Gallery - Image Upload</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" cellspacing="0" cellpadding="0">
    <tr>
    <td><form action="create_thumbnails.php" method="post" enctype="multipart/form-data">
    <p> </p>
    <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0">
    <tr>
    <td><h1>Image Upload Area</h1>
    </td>
    </tr>
    </table>
    <table width="60%" border="0" align="center" cellpadding="5" cellspacing="0">
    <?php
    for ($i = 0; $i < $_POST['num_images']; $i++){
    // Determine alternate row colours
    if($i % 2 == 0){
    $style = "bgcolor=\"#FFFFFF\"";
    $bottomstyle = "bgcolor=\"#FFFFFF\"";
    } else {
    $style = "bgcolor=\"#EFEFEF\"";
    $bottomstyle = "bgcolor=\"#EFEFEF\"";
    }
    echo("\n<tr>\n<td $style width='15%'>Image #" . ($i + 1) . ": </td>\n<td $style><input type='file' name='image[]'></td>\n</tr>");
    echo("\n<tr>\n<td $style width='15%'>Image Title : </td>\n<td $style><input type='text' name='photo_title'></td>\n</tr>");
    echo("\n<tr>\n<td $style valign=\"top\">Photo Description: </td>\n<td $style><textarea name='photo_desc' cols='30' rows='6' wrap='default'></textarea></td>\n</tr>");
    echo("\n<tr>\n<td $style valign=\"top\">Album Cover? </td>\n<td $style><input type=\"radio\" name=\"album_cover\" value=\"$i\">");
    }
    echo("
    <tr>
    <td $style> </td>
    <td $style>
    <input name='process' type='hidden' value='1'>
    <input name='album_id' type='hidden' value='" . $_POST['albums'] . "'>
    <input name='submit' type='submit' id='submit' value='Continue'>
    </td>
    </tr>");
    ?>
    </table>
    <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0" class="bottommenu">
    <tr>
    <td class="bottommenu"><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>
    <?php
    }
    ?>


    The HTML code is straight-forward. We have a simple form, which allows us to indicate the file we want to upload, our image title and description, as well as a radio button allowing us to specify which photo to make our cover.

    <?php
    for ($i = 0; $i < $_POST['num_images']; $i++){
    // Determine alternate row colours
    if($i % 2 == 0){
    $style = "bgcolor=\"#FFFFFF\"";
    $bottomstyle = "bgcolor=\"#FFFFFF\"";
    } else {
    $style = "bgcolor=\"#EFEFEF\"";
    $bottomstyle = "bgcolor=\"#EFEFEF\"";
    }
    echo("\n<tr>\n<td $style width='15%'>Image #" . ($i + 1) . ": </td>\n<td $style><input type='file' name='image[]'></td>\n</tr>");
    echo("\n<tr>\n<td $style width='15%'>Image Title : </td>\n<td $style><input type='text' name='photo_title'></td>\n</tr>");
    echo("\n<tr>\n<td $style valign=\"top\">Photo Description: </td>\n<td $style><textarea name='photo_desc' cols='30' rows='6' wrap='default'></textarea></td>\n</tr>");
    echo("\n<tr>\n<td $style valign=\"top\">Album Cover? </td>\n<td $style><input type=\"radio\" name=\"album_cover\" value=\"$i\">");
    }
    echo("
    <tr>
    <td $style> </td>
    <td $style>
    <input name='process' type='hidden' value='1'>
    <input name='album_id' type='hidden' value='" . $_POST['albums'] . "'>
    <input name='submit' type='submit' id='submit' value='Continue'>
    </td>
    </tr>");
    ?>


    Our PHP code is quite simple as well. We first start off by creating a loop, which will create our upload form. The number of times we loop is determined by the number of images we indicated on the previous page.

    // Determine alternate row colours
    if($i % 2 == 0){
    $style = "bgcolor=\"#FFFFFF\"";
    $bottomstyle = "bgcolor=\"#FFFFFF\"";
    } else {
    $style = "bgcolor=\"#EFEFEF\"";
    $bottomstyle = "bgcolor=\"#EFEFEF\"";
    }


    The code above is simply used to allow an easy screen-flow. We create alternating row colours making use of the modulus (%) operator. We’re simply stating: If the remainder of our loop’s counter, divided by 2, returns 0, use white as the background colour; otherwise, use grey.

    The rest of the form is built using the loop. When we submit the form, the values of the form are sent to our processing page, create_thumbnails.php:

    <?php
    include("GallerySizer.php");
    include("../include/config.php");
    DEFINE("IMAGE_FULL", '../photos/');
    // Album cover
    $cover = $_FILES['image']['name'][$_POST['album_cover']];
    if (!$_REQUEST['process']){
    echo("Error! No images chosen for processing. <br />");
    echo("Click <a href='index.php'>here</a> to start processing your images.");
    die();
    } elseif (!$_POST['album_id']){
    echo("No album selected. Please <a href=\"\">choose an album</a> to upload images to.");
    die();
    } else {
    for($i = 0; $i < count($_FILES['image']['tmp_name']); $i++){
    $fileName = $_FILES['image']['name'][$i];
    copy($_FILES['image']['tmp_name'][$i], IMAGE_FULL . $fileName);
    $thumb = new GallerySizer();
    if($thumb->getLocation($_FILES['image']['name'][$i])){
    if($thumb->loadImage()){
    echo("Still here!");
    if($thumb->getSize()){
    if($thumb->setThumbnail()){
    if($thumb->copyImage()){
    if($thumb->resizeImage()){
    $thumb->copyResize();
    $thumb->display(); 
    }
    }
    }
    }
    } else {
    echo("Invalid image/file has been uploaded. Please upload a supported file-type (JPEG/PNG)"); 
    unlink(IMAGE_FULL . $fileName);
    die();
    }
    insert_location($thumb);
    } else {
    echo("Error processing images: " . mysql_error());
    }
    // If image matches cover selection, update album cover
    if($cover == $_FILES['image']['name'][$i]){
    $sql = "UPDATE albums SET album_cover = '" . $thumb->getThumbLocation() . "' WHERE album_id = " . $_POST['album_id'];
    $result = @mysql_query($sql) or die("Error inserting records: " . mysql_error());

    }
    }
    function insert_location($thumb_obj){
    $image_location = $thumb_obj->getImageLocation();
    $thumb_location = $thumb_obj->getThumbLocation();
    $dbcnx = mysql_connect("localhost", "root", "");
    mysql_select_db("album", $dbcnx);
    $sql = "INSERT INTO photos values(0, '$_POST[photo_title]', '$_POST[photo_desc]', NOW(), '$image_location', '$thumb_location', $_POST[album_id])";
    $result = mysql_query($sql, $dbcnx) or die("Error inserting record(s) into the database: " . mysql_error());
    if ($result){
    echo("Images successfully converted and stored! <br />Click <a href='../admin'>here</a> to continue.");
    }
    }
    ?>


    The code is as follows:

    // Album cover
    $cover = $_FILES['image']['name'][$_POST['album_cover']];


    We store the value of our chosen album, which will be used later on in the script.

    if (!$_REQUEST['process']){
    echo("Error! No images chosen for processing. <br />");
    echo("Click <a href='upload_images.php'>here</a> to start processing your images.");
    die();
    } elseif (!$_POST['album_id']){
    echo("No album selected. Please <a href=\"upload_images.php\">choose an album</a> to upload images to.");
    die();


    Here we simply check to see if the form has been properly submitted via the image_upload script. If the script isn’t properly submitted, we offer a link back to the upload_images script.

    We also check to see if an album ID has been selected, which is determined by the album name drop-down. If no album has been selected, we notify the user, and provide a link back to the upload_images script.

    for($i = 0; $i < count($_FILES['image']['tmp_name']); $i++){
    $fileName = $_FILES['image']['name'][$i];
    copy($_FILES['image']['tmp_name'][$i], IMAGE_FULL . $fileName);
    $thumb = new GallerySizer();
    if($thumb->getLocation($_FILES['image']['name'][$i])){
    if($thumb->loadImage()){
    echo("Still here!");
    if($thumb->getSize()){
    if($thumb->setThumbnail()){
    if($thumb->copyImage()){
    if($thumb->resizeImage()){
    $thumb->copyResize();
    $thumb->display(); 
    }
    }
    }
    }
    } else {
    echo("Invalid image/file has been uploaded. Please upload a supported file-type (JPEG/PNG)"); 
    unlink(IMAGE_FULL . $fileName);
    die();
    }
    insert_location($thumb);
    } else {
    echo("Error processing images: " . mysql_error());
    }
    // If image matches cover selection, update album cover
    if($cover == $_FILES['image']['name'][$i]){
    $sql = "UPDATE albums SET album_cover = '" . $thumb->getThumbLocation() . "' WHERE album_id = " . $_POST['album_id'];
    $result = @mysql_query($sql) or die("Error inserting records: " . mysql_error());

    }


    This here is the chunk of our script. This is also where we finally make use of our GallerySizer class file. We first loop through the files that have been uploaded. We make use of PHP’s global array $_FILES, which allows us to access file information, including: file name, file size, etc.

    In dealing with our files, we first retrieve actual name of the file, and store it into our $fileName variable. When then use PHP’s copy() function, and create a copy of the temporary uploaded file, and store it in our image directory (a constant defined at the top of our script).

    Next, we create an object reference to GallerySizer class. We’ll call our object $thumb. We use our $thumb object to call the getLocation() method (function), and pass to it our the file uploaded from the form. If the function returns a true value, we proceed by calling the loadImage() method, which will then determine if the type of file uploaded is supported by our gallery. If the file uploaded is of an invalid type (not supported), an error message is displayed to the user. If the file is supported, the method returns true, and we then call the getSize() method.

    The getSize() method will determine the dimensions of our uploaded photo, determine the scale for our thumbnail and resized image conversions. If the method returns true, we proceed by calling the setThumbnail() method, which will then convert our uploaded image into a thumbnail. If the method returns true, we call the copyImage() method, which will copy the newly created thumbnail into our specified thumbnail directory. If the copyImage() method operates successfully, it will return true.

    If a true value is returned, we call the resizeImage() method, which will now resize our uploaded image. The size of the image will be less than or equal to our maximum-desired dimensions (set in our GallerySizer class file). If a true value is returned, we then call our last method, copyResize(), which will simply place our newly-resized image into the specified photo directory.

    Because our method-calls are nested, a single failure would cause the entire hierarchy to fail, resulting in the error message – “Error processing image(s)…” – to be displayed.

    Assuming our pass-through into the hierarchy yields a successful conversion process, we call the insert_location() function and pass to it our object reference, $thumb.

    The insert_location() function accepts an object reference, and creates an SQL INSERT statement, which creates a new record of the image in the photos table of our database.

    Our last condition statement:

    if($cover == $_FILES['image']['name'][$i])

    simply checks to see whether or not the current image (in our loop iteration) matches the image chosen as the album cover from the previous image upload page. If the current image is the album cover, we simply create an SQL EDIT statement, which sets the value of the album_cover field to the path of the current image’s thumbnail; thus, resulting in a complete conversion process.

    We then display a message to the user, notifying them that the conversion process was successful.

    Image Editing, Please!

    Well, after we’ve uploaded our images, we may decide that our photo descriptions aren’t what we originally intended. No problem! We’ll add our edit_photos.php script, and making changes to our photo titles and descriptions will be a breeze:

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

    ?>


    The code is identical to our edit_album.php script, except that rather than using our album data, we take the photo data into consideration.

    include_once("../include/config.php");
    // Has album been updated?
    if ( $_POST['edit'] ){
    if ( empty($_POST['photo_title']) || empty($_POST['photo_desc'])){
    $msg = "Please complete all required fields!<br /><a href='edit_photos.php'>Go Back</a>";
    displayPage( $msg, "Error Updating Photo!");
    die();
    }


    We first check to see whether or not the edited photo information has been submitted. If it has, we check to see whether or not the fields were completed. If not, we display an error message to the user. If the fields have been completed, we create an SQL UPDATE statement, and make changes to the photo’s information in the DB:

    $sql = "UPDATE photos SET photo_title = '" . addslashes($_POST['photo_title']) . "', photo_desc = '" . addslashes($_POST['photo_desc']) . "' WHERE photo_id = " . $_POST['photo_id'];
    $result = @mysql_query( $sql ) or die("Error inserting record: " . mysql_error());
    if ($result){
    $msg = "Photo updated successfully!<br /><a href='index.php'>Return to Admin Menu</a>";
    displayPage($msg, "Photo Updated Successfully!");
    die();
    }


    If successful, we notify the user.

    } else if ( !$_POST['edit'] && !empty($_GET['photo_id'])){
    db_connect();
    // Retrieve album information
    $sql = "SELECT photo_id, photo_title, photo_desc FROM photos WHERE photo_id = " . addslashes($_GET['photo_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_photos.php\" method=\"post\">\n";
    $msg .= "<table width=\"60%\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n";
    $msg .= "<tr>\n<td>Photo Title:</td>\n<td><input name=\"photo_title\" type=\"text\" id=\"photo_title\" size=\"40\" value=\"" . $row['photo_title'] . "\"></td>\n</tr>\n";
    $msg .= "<tr>\n<td>Photo Description:</td>\n<td><textarea name=\"photo_desc\" cols=\"30\" rows=\"4\" id=\"photo_desc\">" . $row['photo_desc'] . "</textarea></td>\n</tr>\n";
    $msg .= "<tr>\n<td><input type=\"hidden\" name=\"edit\" value=\"1\"><input type=\"hidden\" name=\"photo_id\" value=\"" . addslashes($_GET['photo_id']) . "\"></td>\n";
    $msg .= "<td><input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Continue\">";
    $msg .= "<a href=\"del_photos.php?photo_id=" . addslashes($_GET['photo_id']) . "\">Delete</a>";
    $msg .= "</td>\n</tr>\n</table>\n</form>";
    $photo_title = $row['photo_title'];
    }
    displayPage($msg, "Editing Photo " . $photo_title . ":"); 


    Next, we verify whether or not the photo information has been edited, and whether or not the photo ID has been submitted. If the page has not been edited, and a photo ID _has_ been specified, we present the user with a form that allows them to edit the pre-existing photo information (title and description). We also provide a link for the image to be deleted from the database. If the user chooses to delete the photo, the photo ID is passed onto our del_photos.php script, which we’ll discuss in a bit.

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


    Lastly, we check to see whether or not a photo ID has been passed to the page. If not, we list all the photos in our database, in a tabular format. Again, we make use of the modulus (%) operator, to determine how many images to display in each row. We then provide a link to edit the photo.

    Our del_photos.php script is very similar to our del_album.php script. The difference, again, is that we take the photo data into consideration, rather than the album data. Our script is as follows:

    <?php
    include_once("../include/config.php");
    // No album id has been selected
    if( !$_GET['photo_id'] ){
    // Display error message to user
    $msg .= "Photo not selected. Please choose a photo you wish to delete!";
    $msg .= "<br /><a href=\"edit_photos.php\">Edit photos</a>";
    displayPage($msg, "Error Selecting Photo");
    } else {
    db_connect();
    // Retrieve image and thumbnail path information
    $sql = "SELECT photo_location, thumbnail_location FROM photos WHERE photo_id = " . addslashes($_GET['photo_id']);
    $result = @mysql_query($sql) or die("Error retrieving records: " . mysql_error());
    while ($row = mysql_fetch_array($result)){ 
    $photo_location = $row['photo_location'];
    $thumb_location = $row['thumbnail_location'];
    }
    if (@unlink("../" . $photo_location)){
    } else {
    die("Error deleting photo!<br /><a href=\"index.php\">Please try again</a>.");
    }
    if (@unlink("../" . $thumb_location)){ 
    } else {
    die("Error deleting thumbnail!<br /><a href=\"index.php\">Please try again</a>.");

    // Delete specified album 
    $sql = "DELETE FROM photos WHERE photo_id = " . addslashes($_GET['photo_id']);
    $result = @mysql_query($sql) or die("Error deleting record: " . mysql_error());
    // Display success to user
    $msg .= "Photo has been successfully deleted!<br /><a href='index.php'>Return to Admin Menu</a>";
    displayPage($msg, "Photo Deleted!");
    }
    ?>


    The code breakdown is as follows:

    include_once("../include/config.php");
    // No album id has been selected
    if( !$_GET['photo_id'] ){
    // Display error message to user
    $msg .= "Photo not selected. Please choose a photo you wish to delete!";
    $msg .= "<br /><a href=\"edit_photos.php\">Edit photos</a>";
    displayPage($msg, "Error Selecting Photo");
    die();


    We first check to see if a photo ID has been submitted. If not, we notify the user by displaying an error message.

    If a photo ID has been specified, we first retrieve the path information for our full-sized image and our thumbnail, which relate to the photo ID specified. Not only do we want to delete the database record, but we also want to delete the actual photo files that reside in the filesystem.

    db_connect();
    // Retrieve image and thumbnail path information
    $sql = "SELECT photo_location, thumbnail_location FROM photos WHERE photo_id = " . addslashes($_GET['photo_id']);
    $result = @mysql_query($sql) or die("Error retrieving records: " . mysql_error());
    while ($row = mysql_fetch_array($result)){ 
    $photo_location = $row['photo_location'];
    $thumb_location = $row['thumbnail_location'];
    }
    if (@unlink("../" . $photo_location)){
    } else {
    die("Error deleting photo!<br /><a href=\"index.php\">Please try again</a>.");
    }
    if (@unlink("../" . $thumb_location)){ 
    } else {
    die("Error deleting thumbnail!<br /><a href=\"index.php\">Please try again</a>.");
    }


    We create an SQL SELECT statement, and retrieve the path information. We then proceed to use PHP’s unlink() function, which performs a delete operation on the file specified as the argument. If there are any errors in the deletion, we echo out an error message, and execution of the script is halted. The user can then try again.

    If both deletions are successful, we create an SQL DELETE statement, and remove the photo record from our database:

    // Delete specified album 
    $sql = "DELETE FROM photos WHERE photo_id = " . addslashes($_GET['photo_id']);
    $result = @mysql_query($sql) or die("Error deleting record: " . mysql_error());
    // Display success to user
    $msg .= "Photo has been successfully deleted!<br /><a href='index.php'>Return to Admin Menu</a>";
    displayPage($msg, "Photo Deleted!");


    If our query is successful, our photo has now been removed both from the filesystem, as well as 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! Best Practices: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Demystifying the automation of custom controls: Part 2. A step-by-step example of using IBM Rational Functional Tester to automate custom controls

    This tutorial applies the concepts that were covered in the first part of this two-part series to a real-world example.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! Rational Build Forge Express eKit

    Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast.
    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! The IBM DB2 Detective Game

    Here's a fun way to learn about DB2! Learn or teach the basics of DB2 and relational database with an interactive game called The DB2 Detective Game. The game teaches relational database concepts and shows how technology can be applied to solving real-life problems (the game's theme is a crime investigation). This tutorial has been updated for DB2 9.
    FREE! Go There Now!


    NEW! Web development with Eclipse Europa, Part 3: Ruby Development Toolkit and RadRails

    It's a good time to be a Web developer. You've never had more choices in terms of technologies. There are so many great open source Web servers, databases, programming languages, and development frameworks. No matter what combination of technologies you prefer to work with, there is a single integrated development environment (IDE) that can increase your productivity: Eclipse. Here in Part 3, we introduce the RDT and RadRails Eclipse plug-ins and show you how to get these plug-ins and start using them. You will learn how to use RadRails to do many common Ruby on Rails development tasks.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    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-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway