I am working on a script to upload an image to the server and insert data to the database. I have 2 parts to this script. The user is not required to upload an image but if they do, I want the script to make sure it is uploaded properly before inserting the data to the database, otherwise if there is no image being uploaded, then just add the data to the database. Below is my code:
if(empty($error)){
if($_POST['pic']){
$uploaddir = '../'.$cat.'Listings/images/';
$uploadfile = $uploaddir . basename($_FILES['pic']['name']);
$pic = basename($_FILES['pic']['name']);
if (move_uploaded_file($_FILES['pic']['tmp_name'], $uploadfile)) {
$sql = "INSERT INTO ".$cat." (`style`, `salePrice`, `leaseRate`, `approxSize`, `sqftForLease`, `landSize`, `municipality`, `zoning`, `notes`, `address`, `city`, `state`, `disclaimer`, `pic`)
VALUES ('$style', '$salePrice', '$leaseRate', '$sqFt', '$sqFtForLease', '$landSize', '$municipality', '$zoning', '$notes', '$address', '$city', '$state', '$disclaimer', '$pic');" or die ('Could not insert into database because: ' . mysql_error());
$insert = mysql_query($sql);
reviseDate();
$address = "";
$city = "";
$state = "";
$disclaimer = "";
$pic = "";
$style = "";
$salePrice = "";
$leaseRate = "";
$sqFt = "";
$sqFtForLease = "";
$landSize = "";
$municipality = "";
$zoning = "";
$notes = "";
$success = true;
}
}elseif(!$_POST['pic']){
$sql = "INSERT INTO ".$cat." (`style`, `salePrice`, `leaseRate`, `approxSize`, `sqftForLease`, `landSize`, `municipality`, `zoning`, `notes`, `address`, `city`, `state`, `disclaimer`, `pic`)
VALUES ('$style', '$salePrice', '$leaseRate', '$sqFt', '$sqFtForLease', '$landSize', '$municipality', '$zoning', '$notes', '$address', '$city', '$state', '$disclaimer', '$pic');" or die ('Could not insert into database because: ' . mysql_error());
$insert = mysql_query($sql);
reviseDate();
$address = "";
$city = "";
$state = "";
$disclaimer = "";
$pic = "";
$style = "";
$salePrice = "";
$leaseRate = "";
$sqFt = "";
$sqFtForLease = "";
$landSize = "";
$municipality = "";
$zoning = "";
$notes = "";
$success = true;
}else{
$error .= "There was a problem uploading the image and therefore no listing was added. Please try again";
}
}
For some reason $_POST['pic'] keeps coming back as an empty string and so no image is ever uploaded it always goes to my elseif(). How do I get it to check to see if the 'pic' file field contains an image to be uploaded? I have also tried using this if($FILES['pic']) to validate it and that doesn't work either.
I am new to uploading files so bear with me. I would also like to know how to validate if the file is a jpg or gif image only. Antything else I want to throw an error.
Any help is appreciated.
Thanks