Solved

Quick Question regarding image names stored in Mysql DB

Posted on 2004-08-19
8
271 Views
Last Modified: 2012-05-05
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
Comment
Question by:theprankstanator
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 4

Accepted Solution

by:
sint4x earned 250 total points
ID: 11850551
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
 
LVL 3

Expert Comment

by:Boris Aranovich
ID: 11856509
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
 

Author Comment

by:theprankstanator
ID: 11900846
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 3

Assisted Solution

by:Boris Aranovich
Boris Aranovich earned 250 total points
ID: 11900901
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
 

Author Comment

by:theprankstanator
ID: 12130019
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
 
LVL 3

Expert Comment

by:Boris Aranovich
ID: 12131418
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
 

Author Comment

by:theprankstanator
ID: 12140358
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
 

Author Comment

by:theprankstanator
ID: 12190201
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question