SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2013
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    delete file and upload new and post new info to db

    I have a table with 4 fields Id - Auto Increment, Date, Category, photo (for this field it just contains the photo name)

    I need to remove previously uploaded photo from server
    upload a new photo
    update the table to reflect the change

    I can delete the file with unlink but then how do I pass the record info to the next part where I can upload a new file and update the record with the new info.
    I have a working script to upload a new photo and update the record but the old file remains on the server
    Code:
      
    <?php
    /* 
     EDIT.PHP
     Allows user to edit specific entry in database
    */
     include('inc_header.php');
    
     // creates the edit record form
     // since this form is used multiple times in this file, I have made it a function that is easily reusable
         function renderForm($Id, $Date, $Catagory, $photo, $error)
          {
     ?>
      <?php 
     // if there are any errors, display them
         if ($error != '')
           {
         echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
     }
     ?> 
         <form method="post" action="upload2.php" enctype="multipart/form-data">
         <table width="600" cellpadding="5" cellspacing="1" border="1">
         <input type="hidden" name="Id" value="<?php echo $Id; ?>"/>
         <tr>
         <td bgcolor="#e9e9e9" align="right">Record ID:</td>
         <td bgcolor="ffffff" align="left"><?php echo $Id; ?></td>
         </tr>
         <tr>
         <input type="hidden" name="Date" value="<?php echo $Date; ?>"/>
         <td bgcolor="#e9e9e9" align="right">Date:</td>
         <td bgcolor="#ffffff" align="left"><?php echo $Date; ?></td>
         </tr>
         <tr>
         <input type="hidden" name="Catagory" value="<?php echo $Catagory; ?>"/>
         <td bgcolor="#e9e9e9" align="right">Catagory:</td>
         <td bgcolor="#ffffff" align="left"><?php echo $Catagory; ?></td>
         </tr>
         <tr>Current Photo - <?php echo $photo; ?>
         <td bgcolor="#e9e9e9" align="right">Photo</td>
         <td bgcolor="#ffffff" align="left"> <input type="file" name="photo" id="photo"></td>
         </tr>
         <tr>
         <td bgcolor="#e9e9e9" align="right">&nbsp;</td>
         <td bgcolor="#ffffff" align="center"><input type="submit" name="submit" value="Submit"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>&nbsp;</td>
         </tr>
         </table>
         </form> 
     </body>
     </html> 
     <?php
     }
     // connect to the database
         include('dbcon.php');
     
     // check if the form has been submitted. If it has, process the form and save it to the database
         if (isset($_POST['submit']))
    
           { 
     // confirm that the 'id' value is a valid integer before getting the form data
         if (is_numeric($_POST['Id']))
          {
    
     // get form data, making sure it is valid
          $Id = $_POST['Id'];
          $Date = $_POST['Date'];
          $Catagory = $_POST['Catagory']; 
          $photo=($_FILES['photo']['name']);
    
    // check that fields you want required are filled in
         if ($Catagory == '')
          {
     // generate error message
          $error = 'ERROR: Please fill in all required fields!';
     
     //error, display form
          renderForm($Id, $Date, $Catagory, $photo, $error);
     }
       else
          {
     // save the data to the database
          mysql_query("UPDATE test SET  Date='$Date', Catagory='$Catagory', photo='$photo' WHERE Id='$Id'")
     or die(mysql_error()); 
         }
     }
     else
          {
     // if the 'id' isn't valid, display an error
          echo 'Error!';
        }
     }
          else
     // if the form hasn't been submitted, get the data from the db and display the form
          {
     
     // get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
         if (isset($_GET['Id']) && is_numeric($_GET['Id']) && $_GET['Id'] > 0)
           {
     // query db
         $Id = $_GET['Id'];
         $result = mysql_query("SELECT * FROM test WHERE Id=$Id")
         or die(mysql_error()); 
         $row = mysql_fetch_array($result);
     
     // check that the 'id' matches up with a row in the database
           if($row)
            {
     
     // get data from db
         $Id = $row['Id'];
         $Date = $row['Date'];
         $Catagory = $row['Catagory'];
         $photo = $row['photo'];
    
     // show form
           renderForm($Id, $Date, $Catagory, $photo, $error);
            }
          else
     // if no match, display result
          {
          echo "No results!";
          }
     }
           else
     // if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
            {
           echo 'Error!';
          }
     }
    ?>
    And the upload file
    Code:
    <?php
    
    ///DEBUGGING
    if (!empty($_POST)) {
       print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>"; 
    }
    
    //This gets all the other information from the form
       $id        = isset($_POST['Id'])        ? $_POST['Id']        : 'NULL'; 
       $date      = isset($_POST['Date'])      ? $_POST['Date']      : ''; 
       $catagory      = isset($_POST['Catagory'])      ? $_POST['Catagory']      : ''; 
       $photo=($_FILES['photo']['name']);  
    
    
    // Connects to your Database
     require('dbcadmin.php');
    /////////////////////
    
    
    /////////////////////
    
    $folder = $_POST['Catagory'];  
      include('class.upload.php');
    //Check that we have a file
    
       // we instanciate the class for each element of $file
             $handle = new Upload($_FILES['photo']);
    
            // then we check if the file has been uploaded properly
            // in its *temporary* location in the server (often, it is /tmp)
            if ($handle->uploaded) {
           $handle->auto_create_dir = false;
           $handle->image_resize         = true;
           $handle->image_x              = 600;
           $handle->image_ratio_y        = true;
    
                // now, we start the upload 'process'. That is, to copy the uploaded file
                // from its temporary location to the wanted location
                // It could be something like $handle->Process('/home/www/my_uploads/');
            $handle->process('/home/xxxxxxxxx/public_html/test/images/'.$folder);
    
                // we check if everything went OK
                  if ($handle->processed) {
               echo '<center><p>Image resized and uploaded to ' .$folder;
                    // everything was fine !
                 echo ' &nbsp; <a href="recipesview-pages.php">Go Back</a></p>';
                } else {
                    // one error occured
                    echo '<p class="result">';
                    echo '  <b>File not uploaded to the wanted location</b><br />';
                    echo '  Error: ' . $handle->error . '';
                    echo '</p>';
                }
    
    
            } else {
                // if we're here, the upload file failed for some reasons
                // i.e. the server didn't receive the file
                echo '<center><p class="result">';
                echo '  <b>No file chosen for upload</b><br />';
                echo ' ' . $handle->error . '';
                echo '</p>';
            }
      
    
    ?>
    As I said those 2 files work awesome, I just have no idea where to put the unlink info. Thanks in advance. I apologize if I posted to much info.

  2. #2
    From space with love silver trophy
    SpacePhoenix's Avatar
    Join Date
    May 2007
    Location
    Poole, UK
    Posts
    5,019
    Mentioned
    103 Post(s)
    Tagged
    0 Thread(s)
    Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn't tie you down so much to a particular database server software.

    Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.
    Community Team Advisor
    Forum Guidelines: Posting FAQ Signatures FAQ Self Promotion FAQ
    Help the Mods: What's Fluff? Report Fluff/Spam to a Moderator

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2013
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Am In the process

    Quote Originally Posted by SpacePhoenix View Post
    Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn't tie you down so much to a particular database server software.

    Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.
    Okay I get that and I just went through and changed them over. Would you like me to post the new code? But that does not help with my question.

  4. #4
    SitePoint Member
    Join Date
    Dec 2013
    Posts
    20
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there,
    The unlink info should be put after the photo uploaded successful and before you update the db recored.For example,
    Code:
    // we check if everything went OK
                  if ($handle->processed) {
               //Get the old photo name
               $old = "";
               @unlink($old);
               //Update
               $sql = "UPDATE test SET photo='$new' WHERE id='$id'";
               mysql_query($sql);            
                
               echo '<center><p>Image resized and uploaded to ' .$folder;
                    // everything was fine !
                 echo ' &nbsp; <a href="recipesview-pages.php">Go Back</a></p>';
                }
    Hope that helps.

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2013
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    It wasn't working after all

    Quote Originally Posted by blue_sky View Post
    Hi there,
    The unlink info should be put after the photo uploaded successful and before you update the db recored.For example,
    Code:
    // we check if everything went OK
                  if ($handle->processed) {
               //Get the old photo name
               $old = "";
               @unlink($old);
               //Update
               $sql = "UPDATE test SET photo='$new' WHERE id='$id'";
               mysql_query($sql);            
                
               echo '<center><p>Image resized and uploaded to ' .$folder;
                    // everything was fine !
                 echo ' &nbsp; <a href="recipesview-pages.php">Go Back</a></p>';
                }
    Hope that helps.
    I guess it wasn't working :{ was looking at the wrong record (DUH) so now the problem is I can get it to upload a photo but I can't get it to update the photo info in the db field or delete the old photo Arggh Frustrating


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •