Here's the deal. I am getting into uploading multiple images with a record details. Image file paths are stored in "images" table and records are stored in "records" table. They both work fine separately. I am just having issue using both of them together since "foreach loop" is involved. I want to make sure the image is uploaded and check for errors before inserting the image and record details. Since this for uploading "multiple files", all this checking for errors is inside "foreach loop". It will insert the images fine, but it will also insert the record details multiple times(depending on the images attached) in the records table. If I insert the record details outside the loop, it'll insert only once but then it'll insert the data with or without the images attached.
Here's a basic set up of what I am talking about . I removed the extra code. I just would like to know where I can place the insert into records code relative to the foreach loop so that It checks the errors for file uploads and inserts details in to the database after that.
if(isset($_POST['submit']) {
$record_name = trim($_POST['record_name']);
$record_details = trim($_POST['record_details']);
$record_type = trim($_POST['record_type']);
$date = date('Y-m-d H:i:s');
if(empty($record_name)) {
echo 'record name is required!';
} else if(empty($record_details)) {
$error = 'record details are required!';
} else if(empty($record_type)) {
$error = 'Type is required!';
} else {
if(isset($_FILES['files'])){
$userdir = $_SERVER['DOCUMENT_ROOT'] .'/comp/images/';
if(!is_dir($userdir)){
mkdir($userdir, 0775, true);
}
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(is_uploaded_file($_FILES['files']['tmp_name'][$key])) {
if(in_array($type, $allowed)) {
try {
$insert_image = $db->prepare("INSERT INTO images(record_id, image_path, date) VALUES(:record_id, :image_path, :date)");
$insert_image->bindParam(':record_id', $record_id);
$insert_image->bindParam(':image_path', $image_path);
$insert_image->bindParam(':date', $date_added);
$result_image = $insert_image->execute();
if($result_image == false) {
echo 'There was a problem!';
} else {
move_uploaded_file($temp, $file_path);
echo 'Your image has been saved.';
}
$insert_record = $db->prepare("INSERT INTO records(record_name, record_type, record_details, date)
VALUES(:record_name, :record_type, :record_details, :date)");
$insert_record->bindParam(':record_name', $record_name);
$insert_record->bindParam(':record_type', $record_type);
$insert_record->bindParam(':record_details', $record_details );
$insert_record->bindParam(':date', $date);
$result_record = $insert_record->execute();
if($result_record == true) {
echo 'Your record has been saved.';
} else {
$error = 'record not added!';
}
} catch(Exception $e) {
$error = die($e->getMessage());
}
} else {
echo 'You have uploaded a forbidden extension!';
}
} else {
echo 'File is empty!';
}
}
}
}
}