• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 281
  • Last Modified:

Quick Question regarding image names stored in Mysql DB

Hi Guys,

I have a form where people can upload data and an image to a db. If they do not upload an image, they can edit their entry later and add an image then.
However (and this is the issue) if they add an image and THEN go and edit the details, it deletes the image name from the db, this is because if they do not upload an image when they edit the form, it submits $_POST['image'] (as a hidden form variable) to the db, but if they DO upload an image it submits $pic_name. Now, because in my INSERT/UPDATE staements, for the column 'image' I have specified $pic_name to be INSERTed/UPDATEd... does this make sense? Its kinda hard to summarise... Basically, I need to create an if statement (maybe?) that says that if no image is uploaded, to INSERT/UPDATE $_POST['image'] or if an image is uploaded, to INSERT/UPDATE $pic_name.....

sheeesh ! does that make sense?

Thanks all!

Christian
0
theprankstanator
Asked:
theprankstanator
  • 4
  • 3
2 Solutions
 
sint4xCommented:
Just do a simple check:
Here's something similar to what I have used using the $_FILES array.

$uploaddir = $_SERVER["DOCUMENT_ROOT"] . "/uploads/"; // yoursite.com/uploads/

if (move_uploaded_file($_FILES['image']['tmp_name'], $uploaddir . $_FILES['image']['name']))
{
    // then image is uploaded, update the filename with ur sql.
}
elseif($_FILES['image']['name'] == '')
{
    // image is empty and will not upload, build ur sql without the image field
}

I hope this helps!
0
 
Boris AranovichSenior Software EngineerCommented:
Just ignore the image field if there wasn't any real image.
Or, add a hidden field that will always contain the name of the stored image,
and when there is some new image uploaded, just replace the value before the insert/update statement.
0
 
theprankstanatorAuthor Commented:
Well, I have used this so far, but it still over-writes the images if none are uploaded..

<?php
      if ($row_pplay['image'] == TRUE) {
      echo '<input type="hidden" name="image" value="'.$row_pplay['image'].'"><a href="../images/parts/'.$row_pplay['image'].'" target="_blank"><img src="../images/parts/thumbs/tn_'.$row_pplay['image'].'" border="0"/></a>';
      } else if ($row_pplay['image'] == FALSE) {
      echo 'Image:<br /><input type="file" name="image" class="formfield"><br/>';
      }
?>
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Boris AranovichSenior Software EngineerCommented:
actually, what I meant is:

echo '<input type="hidden" name="origImage" value="'.htmlspecialchars($row_pplay['image']).'" />';
echo '<input type="file" name="newImage" class="formfield" />'."\n";

and after you submit the form, in the function that inserts to the DB, do something like that:

$insertImageName = $_POST['origImage'];

if .... there was new image and it was uploaded correctly .... then {
   $insertImageName = $newInsertedImagefile;
}
0
 
theprankstanatorAuthor Commented:
Hi Nomaed,

Sorry for taking so long to get back... I am still having issues - can you re-write that in more lamens terms? (I am new to PHP).

Thanks.

0
 
Boris AranovichSenior Software EngineerCommented:
I guess that the only part that you don't fully understand is:
if .... there was new image and it was uploaded correctly .... then {
   $insertImageName = $newInsertedImagefile;
}

then, what I mean is:

// sets the image name to be the default image, that was sent from the database, which is
// equal to the old image name (it was some hidden field)
$image = $_POST['image'];

// now we also had a field with New image Upload, so we proccess it
    if (isset($_FILES['image_upl']) and isset($_FILES['image_upl']['name']))
    {
        $nm = 'somepath/image_'.time(); // some random filename, so no overwrites will occur, consist of current timestamp and prefix

        // the switch sets the new filename extension based on file type that was uploaded
        switch($_FILES['image_upl']['type'])
        {
            case 'image/jpeg':
            case 'image/pjpeg':
                $nm .= '.jpg';
                break;
            case 'image/gif':
                $nm .= '.gif';
                break;
            case 'image/x-png':
            case 'image/png':
                $nm .= '.png';
                break;
            default:
                // other files should give error, cause they are not allowed
                $nm = 'error!!!';
                break;
        }
        // if there was no error (correct image type, and file was moved to the destination directory)
        if (($nm != 'error!!!') and (move_uploaded_file($_FILES['image_upl']['tmp_name'], $nm))) {
            // we overwrite the original filename to the new filename, that we just uploaded
            $image = $nm;
        } else {
            // if there was error with file type or moving it to the destination directory, we just delete the temporary file
            unlink($_FILES['image_upl']['tmp_name']);
        }
    }


/* now goes the query, which is for example something like this,
it updates the image filename (either original, or if upload succeeded, new filename) */
$sql = "UPDATE table SET somefileds='soemvalues', ...., image='{$image}' WHERE id='{$id}';";
.... etc..
0
 
theprankstanatorAuthor Commented:
Hi Nomaed,

I am so close now I can smell it, but I am having a hard time integrating that script with one that I am using to make thumbnails...

*********************************
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
function resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp) {
     $g_srcfile=$sourcefile;
     
     if(file_exists($sourcefile)) {
          //Get data from source image
          $g_is=getimagesize($sourcefile);
          $p = pathinfo($sourcefile);
          switch ($p['extension']) {
               case 'gif':
                    $img_src=imagecreatefromgif($sourcefile);
                    break;
               case 'jpg':
               case 'jpeg':
                    $img_src=imagecreatefromjpeg($sourcefile);
                    break;
               case 'png':
                    $img_src=imagecreatefrompng($sourcefile);
                    break;
               default:
                    return false; //Can't handle other formats
          }
               //Create preview sized image
          if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
               $g_fw=$psize;
               $g_fh=$psize;
               if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                    $g_iw=$g_fw;
                    $g_ih=($g_fw/$g_is[0])*$g_is[1];
               } else {
                    $g_ih=$g_fh;
                    $g_iw=($g_ih/$g_is[1])*$g_is[0];
               }
               $img_dst=imagecreatetruecolor($g_iw,$g_ih);
               imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
          } else { //Just copy the image
               $img_dst = $img_src;
          }
          imageinterlace($img_dst, 1);
          imagejpeg($img_dst, $pdestfile, $g_imgcomp);
          imagedestroy($img_dst);
          return true;
     } else {
          return false;
     }
}

//Check that there was actually an upload before proceeding
if (count($_FILES) > 0 and array_key_exists('image', $_FILES)) {
     if (is_uploaded_file($_FILES['image']['tmp_name'])) {
          if ($_FILES['image']['name'] != '')
          {
               $pic_name = "1_" . date("d_m_Y_H_i") . "_" . $_FILES['image']['name'];
          } else {
               exit; //Can't really do anything if we don't have a filename
          }
          $uploaddir = '../images/parts/';
          $thumbnaildir = '../images/parts/thumbs/';
          $sourcefile = $uploaddir.$pic_name;
          move_uploaded_file($_FILES['image']['tmp_name'], $sourcefile);
          $pdestfile = "{$thumbnaildir}tn_{$pic_name}";

          $g_imgcomp = 50;
          $psize = 150;
          resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp);
     }
}
*********************************

Any suggestions?

Thanks so much!

Christian
0
 
theprankstanatorAuthor Commented:
Well, i did it with a very simple way....

                        if ($_FILES['image']['name'] != '') {
                                                $updateSQL = sprintf("UPDATE  blah blah blah.... ");
                        } else {
                                                          $updateSQL = sprintf("UPDATE  blah blah blah.... ");
                        }

Thanks guys for your help, I am going to split points cause I wouldn't have gotten to this without both your help..

Christian
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now