Forum Moderators: coopster
$image=0; and it always removes the existing image from the database.
if(isset($_POST['submit']))
{
if(!empty($_FILES['image']))
{
$image=$_FILES['image']['name'];
include "upload.inc.php";
$proc = new upload;
$proc->set_max_size(180000);
$proc->set_directory("/images/");
$proc->set_tmp_name($_FILES['image']['tmp_name']);
$proc->set_file_size($_FILES['image']['size']);
$proc->set_file_type($_FILES['image']['type']);
$proc->set_file_name($_FILES['image']['name']);
$proc->start_copy();
}
else
{
$image=0;
}
$updatelink="Update table set image='$image' where ID='$ID'";
mysql_query($updatelink) or die("Could not update");
print "Image Updated";
}
}
Anyway, the reason it removes the existing image is that you always run the query. You should only run the query if there is an actual image to run it with. In other words, the last few lines should be within the "if" block that tests for whether or not the image was uploaded.
Another thing. I usually do it with a bit more convoluted sequence, roughly as follows. Assume that the filename of the new file is img_file.img and the existing image was named old_image.img
- check to see whether the user has uploaded an image (as you have done).
- rename the existing image to something like old_image.img.timestamp.bk
- check to see whether a file named img_file.img exists already [php.net].
- if so, start looping and try img_file_1.img, img_file_2.img etc until I find a unique name.
- once I have a unique name, move the file to the drectory where I want it and save it as img_file_7.img (for example).
- verify that the new file_exists() [php.net] and the save was successful
- if so, update the database with the name of the new file and delete the old file.
- if not, leave the db alone and rename old_image.img.timestamp.bk back to old_image.img
That reduces the chance of accidentally overwriting files and ending up with broken image links or updating the db to point to a file that was not successfully saved.
Cheers,
Tom
[edited by: ergophobe at 3:35 am (utc) on Nov. 26, 2004]
I did what you suggested and moved the query to within the "if" block because it makes sense.
But after much frustration and rechecking I found an error in my code that was causing the problem:
if(!empty($_FILES['image'])) should have been
if(!empty($_FILES['image'][b]['name'][/b])) Thanks again. I'm gonna have fun building your convoluted sequence :)