I have a page that inserts records into a table. what i am having a little bit of trouble with, is if the user decides that he does not want to include a picture, how do i submit the form without errors. Or is there a way to set the file field to select a default image from a folder and set it as the file entry if there is no selection from the user?
I have been able to solve the problem. Below is the code:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ($_FILES['photo'] && $_FILES['photo']['error'] == 0) {
$set['photo'] = "'" . $pix . "'";
$image = @getimagesize($_FILES['photo']['tmp_name']);
$size = ($_FILES["photo"]["size"]<= 512000);
if($image && $size = TRUE)
$pix= $_FILES['photo']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$photo= rand()."_".time().".".$pixExt;
$tmpName = $_FILES['photo']['tmp_name'];
$target = "../events/";
$target = $target . $photo;
}
move_uploaded_file($tmpName, $target);
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "pd")) {
$insertSQL = sprintf("INSERT INTO events (title, detail, `date`, photo) VALUES (%s, %s, %s, '$photo')",
GetSQLValueString($_POST['title'], "text"),
GetSQLValueString($_POST['detail'], "text"),
GetSQLValueString($_POST['date'], "text"));
mysql_select_db($database_connMain, $connMain);
$Result1 = mysql_query($insertSQL, $connMain) or die(mysql_error());
$insertGoTo = "confirm.php?user=" . $row_rsadmin['aID'] . "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
If the user is allowed to store the data without sendign a picture, then it is not a very good idea to do the recording only if the file upload was successful.
You should restructure the code, so that the image upload only happens if there is an image uploaded, so all the code that involves
$_FILES['photo']should be inside a block as such:Also it is important to handle the database functions outside of this block, so you have to create a the record set outside of the file upload block, and add the image related values inside.
This way you handle the errors if the user doesn’t upload a picture, and also make it possible to record the data without it.
Edit: I have modified the above code to reflect the need that the photo field is always present in the insert statement.
Edit 2: I fully implemented the file upload block in this edit, to get closer to the askers actual situation, also keeping it universal.