Solved

Quick Question regarding image names stored in Mysql DB

Posted on 2004-08-19
8
262 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
  • 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

912 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now