Link to home
Start Free TrialLog in
Avatar of cataleptic_state
cataleptic_stateFlag for United Kingdom of Great Britain and Northern Ireland

asked on

file field update/upload problem

I have a profile update page, with a file field where the user can upload a photo.


But I have a major problem. I know that the fileupload form cannot contain a value from a database.


When I submit the form without the image, it resets the photo field to blank.


I would like to know:

How can I upload a photo with checking if the same name is already in the folder?

How can I leave the field intact so that the current image stays on blank field?

 

This is my code


if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "update_business")) {
  $updateSQL = sprintf("UPDATE users SET company_name=%s, comp_add1=%s, comp_add2=%s, comp_add3=%s, comp_city=%s, comp_postcode=%s, comp_tel=%s, comp_fax=%s, comp_email=%s, comp_web=%s, comp_description=%s, honors_awards=%s, industry=%s, logo=%s, bul1=%s, bul2=%s, bul3=%s, bul4=%s, bul5=%s, bul6=%s WHERE user_id=%s",
                       GetSQLValueString($_POST['company_name'], "text"),
                       GetSQLValueString($_POST['comp_add1'], "text"),
                       GetSQLValueString($_POST['comp_add2'], "text"),
                       GetSQLValueString($_POST['comp_add3'], "text"),
                       GetSQLValueString($_POST['comp_city'], "text"),
                       GetSQLValueString($_POST['comp_postcode'], "text"),
                       GetSQLValueString($_POST['comp_tel'], "text"),
                       GetSQLValueString($_POST['comp_fax'], "text"),
                       GetSQLValueString($_POST['comp_email'], "text"),
                       GetSQLValueString($_POST['comp_web'], "text"),
                       GetSQLValueString($_POST['comp_description'], "text"),
                       GetSQLValueString($_POST['honors_awards'], "text"),
                       GetSQLValueString($_POST['industry'], "text"),
                       GetSQLValueString($_FILES['ufile']['name'], "text"),
                       GetSQLValueString($_POST['bul1'], "text"),
                       GetSQLValueString($_POST['bul2'], "text"),
                       GetSQLValueString($_POST['bul3'], "text"),
                       GetSQLValueString($_POST['bul4'], "text"),
                       GetSQLValueString($_POST['bul5'], "text"),
                       GetSQLValueString($_POST['bul6'], "text"),
                       GetSQLValueString($_POST['user'], "int"));



  mysql_select_db($database_db, $db);
  $Result1 = mysql_query($updateSQL, $db) or die(mysql_error());


  $updateGoTo = "home.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}


if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "update_business")) {
  $updateSQL = sprintf("UPDATE users SET photo=%s WHERE user_id=%s",
                       GetSQLValueString($_FILES['ufile']['name'], "text"),
                       GetSQLValueString($_POST['user'], "int"));


  mysql_select_db($database_db, $db);
  $Result1 = mysql_query($updateSQL, $db) or die(mysql_error());
}
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","50000");


//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }


//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
     //reads the name of the file the user submitted for uploading
     $image=$_FILES['ufile']['name'];
     //if it is not empty
     if ($image)
     {
     //get the original name of the file from the clients machine
         $filename = stripslashes($_FILES['ufile']['name']);
     //get the extension of the file in a lower case format
          $extension = getExtension($filename);
         $extension = strtolower($extension);
     //if it is not a known extension, we will suppose it is an error and will not  upload the file,
    //otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
         {
        //print error message
             echo '<h1>Unknown extension!</h1>';
             $errors=1;
         }
         else
         {
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['ufile']['tmp_name']);


//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
}


//we will give an unique name, for example the time in unix time format
//$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="company_pics/".$image;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['ufile']['tmp_name'], $newname);
if (!$copied)
{
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
}}}}


//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
     echo "<h1>File Uploaded Successfully!</h1>";
 }


<label>Upload Photo</label><br />
<input name="ufile" type="file" id="ufile" size="50" />
<br /><br />


Avatar of theremon
theremon
Flag of Greece image

Hi there

I believe that the answer to your problem is actually a lot simpler than you think.
Personally, what I do is prepare my sql statement having a variable in place of the actual field/value combination. Before sending that sql statement to the server, I check if the file has been uploaded. If so, I set the variable to something like ", Filename='" . $_FILES['ufile']['name'] ."'", otherwise just to an empty string.
Then I replace that in the sql statement and send it to the server.
That way, when updating, the file field does not get replaced if no file has been uploaded.
Consider the following change to your code:
// This sets $newFilename to either an empty string or to the uploaded file's filename in an update clause parameter.
$newFilename=($_FILES['ufile']['name']!="" ? ", logo=" . GetSQLValueString($_FILES['ufile']['name'], "text") : "");

// Here, I replaced "logo=%s" with a plain "%s", since the "logo=" has been prepended to the filename in the statement above.

$updateSQL = sprintf("UPDATE users SET company_name=%s, comp_add1=%s, comp_add2=%s, comp_add3=%s, comp_city=%s, comp_postcode=%s, comp_tel=%s, comp_fax=%s, comp_email=%s, comp_web=%s, comp_description=%s, honors_awards=%s, industry=%s %s, bul1=%s, bul2=%s, bul3=%s, bul4=%s, bul5=%s, bul6=%s WHERE user_id=%s",
                       GetSQLValueString($_POST['company_name'], "text"),
                       GetSQLValueString($_POST['comp_add1'], "text"),
                       GetSQLValueString($_POST['comp_add2'], "text"),
                       GetSQLValueString($_POST['comp_add3'], "text"),
                       GetSQLValueString($_POST['comp_city'], "text"),
                       GetSQLValueString($_POST['comp_postcode'], "text"),
                       GetSQLValueString($_POST['comp_tel'], "text"),
                       GetSQLValueString($_POST['comp_fax'], "text"),
                       GetSQLValueString($_POST['comp_email'], "text"),
                       GetSQLValueString($_POST['comp_web'], "text"),
                       GetSQLValueString($_POST['comp_description'], "text"),
                       GetSQLValueString($_POST['honors_awards'], "text"),
                       GetSQLValueString($_POST['industry'], "text"),
                       $newFilename,
                       GetSQLValueString($_POST['bul1'], "text"),
                       GetSQLValueString($_POST['bul2'], "text"),
                       GetSQLValueString($_POST['bul3'], "text"),
                       GetSQLValueString($_POST['bul4'], "text"),
                       GetSQLValueString($_POST['bul5'], "text"),
                       GetSQLValueString($_POST['bul6'], "text"),
                       GetSQLValueString($_POST['user'], "int"));

Open in new window

One more thing:
If possible, you should also consider changing the hand-coded file extension checking function with something like the PHP built-in function getimagesize ( http://php.net/manual/en/function.getimagesize.php )
This returns the mime type of the file after reading it and can help you overcome problems such as text files that have been renamed to "something.jpg"
Avatar of cataleptic_state

ASKER

Can I do this:
// This sets $newFilename to either an empty string or to the uploaded file's filename in an update clause parameter.
$newFilename=($_FILES['ufile']['name']!="" ? ", logo=" . GetSQLValueString($_FILES['ufile']['name'], "text") : $row_user_profile['photo']);

I want the previous filename to stay intact. This is $row_user_profile['photo']

Do I need to add anything else to this?
Hi again

no, actually you don't need to do anything. When you issue an UPDATE statement for a row (or multiple rows), only the fields you specify are updated. All other fields of the record stay intact. For example, consider a table called People consisting of id, FirstName, LastName fields.
Say you have a record with the following data:
1, George, Smith
The statement:
Update People set FirstName='John' where id=1 will simply result in:
1, John, Smith

The statement:
Update People set FirstName='John', LastName='Doe' where id=1 will result in:
1, John, Doe

So, in your assignment above, there's no reason to try adding the old filename. What my assignment did was assign the value: , logo='FILENAME' to $newFilename if only you had some input, otherwise it left $newFilename empty. When $newFilename is appended to the UPDATE statement, it either updates the field or not. You don't have to pass the old filename back to the UPDATE statement.
OK, so I can remove the field and add a page new page just for file upload script and that would eliminate the need to update the image field on the code above? The thing is I wanted everything to be on same page
No, don't set up a new page. Leave everything as is.
By doing what I proposed, the result will be that whenever someone chooses to upload a file, the file will get uploaded and the database will be updated accordingly. If a user on the very same form, does NOT select any file for upload, the database field value will stay intact.
Ok, I am really sorry I have taken the function out, I can put it back in, coz It didnt work before anyway
Hi, the page does not seem to upload the image, but it says uploaded successfully.

Also where do I put the image upload script in the code?
Hi again

what is you exact code at the moment?
The code you initially posted is lacking a few things and also has html mixed with php without escaping etc.
Can you post your code using a file attachment or the code input field, so that we get an idea of what's it like right now?
Thanks
Hi I have changed to to have a link that takes me to another page to upload.

I will however post the new old file so that you may take a look. If you get it to work I will revert back and then award you the points.

As I want everything on 1 page.
//define a maxim size for the uploaded images  in Kb
 define ("MAX_SIZE","5000000");


//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }


//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
     //reads the name of the file the user submitted for uploading
     $image=$_FILES['ufile']['name'];
     //if it is not empty
     if ($image)
     {
     //get the original name of the file from the clients machine
         $filename = stripslashes($_FILES['ufile']['name']);
     //get the extension of the file in a lower case format
          $extension = getExtension($filename);
         $extension = strtolower($extension);
     //if it is not a known extension, we will suppose it is an error and will not  upload the file,
    //otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
         {
        //print error message
             echo '<h1>Unknown extension!</h1>';
             $errors=1;
         }
         else
         {
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['ufile']['tmp_name']);


//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
}


//we will give an unique name, for example the time in unix time format
//$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="user_pics/".$image;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['ufile']['tmp_name'], $newname);
if (!$copied)
{
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
}}}}


//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
     echo "<h1>File Uploaded Successfully!</h1>";
 }

// This sets $newFilename to either an empty string or to the uploaded file's filename in an update clause parameter.
$newFilename=($_FILES['ufile']['name']!="" ? ", photo=" . GetSQLValueString($_FILES['ufile']['name'], "text") : "");

// Here, I replaced "logo=%s" with a plain "%s", since the "logo=" has been prepended to the filename in the statement above.


if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "update_business")) {
$updateSQL = sprintf("UPDATE users SET company_name=%s, comp_add1=%s, comp_add2=%s, comp_add3=%s, comp_city=%s, comp_postcode=%s, comp_tel=%s, comp_fax=%s, comp_email=%s, comp_web=%s, comp_description=%s, honors_awards=%s, industry=%s, %s, bul1=%s, bul2=%s, bul3=%s, bul4=%s, bul5=%s, bul6=%s WHERE user_id=%s",
                       GetSQLValueString($_POST['company_name'], "text"),
                       GetSQLValueString($_POST['comp_add1'], "text"),
                       GetSQLValueString($_POST['comp_add2'], "text"),
                       GetSQLValueString($_POST['comp_add3'], "text"),
                       GetSQLValueString($_POST['comp_city'], "text"),
                       GetSQLValueString($_POST['comp_postcode'], "text"),
                       GetSQLValueString($_POST['comp_tel'], "text"),
                       GetSQLValueString($_POST['comp_fax'], "text"),
                       GetSQLValueString($_POST['comp_email'], "text"),
                       GetSQLValueString($_POST['comp_web'], "text"),
                       GetSQLValueString($_POST['comp_description'], "text"),
                       GetSQLValueString($_POST['honors_awards'], "text"),
                       GetSQLValueString($_POST['industry'], "text"),
                       $newFilename,
                       GetSQLValueString($_POST['bul1'], "text"),
                       GetSQLValueString($_POST['bul2'], "text"),
                       GetSQLValueString($_POST['bul3'], "text"),
                       GetSQLValueString($_POST['bul4'], "text"),
                       GetSQLValueString($_POST['bul5'], "text"),
                       GetSQLValueString($_POST['bul6'], "text"),
                       GetSQLValueString($_POST['user'], "int"));



  mysql_select_db($database_db, $db);
  $Result1 = mysql_query($updateSQL, $db) or die(mysql_error());


  $updateGoTo = "home.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

/*
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "update_business")) {
  $updateSQL = sprintf("UPDATE users SET photo=%s WHERE user_id=%s",
                       GetSQLValueString($_FILES['ufile']['name'], "text"),
                       GetSQLValueString($_POST['user'], "int"));


  mysql_select_db($database_db, $db);
  $Result1 = mysql_query($updateSQL, $db) or die(mysql_error());
}
*/

Open in new window

Hi again

two things after taking a quick look at your code:
1. That piece of code references variables and functions that are not in the code and it doesn't have any include() or require() statements. It can't work as it is. It doesn't even have the html form needed to upload the data.
2. I can't simply "make it work" as it is. The logic of the code looks ok, even though there are a couple of things that can and should be changed - for instance, the sql updating code is outside the if statement that checks whether the form has been posted - this means that it will be constantly executed with varying (and certainly unwanted) results. That being said, you should change line 66 of the above code from: }}}}
to: }}}
and add a closing } at the end.

Finally, please note that checking why the form doesn't upload and fixing the code to make sure it does, is not even totally code-related. There could even be issues with the server folder permissions - for instance, the folder "user_pics" may not have proper permissions. Checking and fixing all of this is totally different from your initial question.
Hi I have only included the problem code if you want the full php page code I will send you that.

What I sent you is just the upload portion of the code.
Hi again

yes, having the code will help.
Please consider however to open a new question for this problem. As I said before the fact that your code does not upload is a totally different issue than the one in your initial question.
Here is the page.

The question is still regarding the upload/update
edit-profile.php
Hi still need a solution to this hence put the points up
anyone?
ASKER CERTIFIED SOLUTION
Avatar of cataleptic_state
cataleptic_state
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial