I've made simple PHP & MySQL crud with two image upload button to save two image to one database in different column like:
It works fine with one upload one image and saved to database, but when I add another button to try upload two image there's no error and it cannot storred in database.
Here is my small code:
<?php
include 'connection.php';
$temp = "upload/";
if (!file_exists($temp))
mkdir($temp);
$name = $_POST['name'];
$address = $_POST['address'];
$fileupload = $_FILES['fileupload']['tmp_name'];
$ImageName = $_FILES['fileupload']['name'];
$ImageType = $_FILES['fileupload']['type'];
if (!empty($fileupload)){
$random = rand(11111111, 99999999);
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt); // Extension
$ImageName = preg_replace("/.[^.s]{3,4}$/", "", $ImageName);
$NewImageName = str_replace(' ', '', $random.'.'.$ImageExt);
move_uploaded_file($_FILES["file_upload"]["tmp_name"], $temp.$NewImageName);
$query = "INSERT into table_fileupload (name, address, image_1, image_2) VALUES (?, ?, ?, ?)";
$dewan1 = $db1->prepare($query);
$dewan1->bind_param("sss", $name, $address, $NewImageName, $NewImageName);
$dewan1->execute();
echo "Success!";
} else {
echo "Error!";
}
?>
HTML:
<form id="form-data">
........................
........................
........................
<div class="form-group">
<label>image 1</label>
<input type="file" name="fileupload" id="fileupload" class="form-control" />
</div>
<div class="form-group">
<label>image 2</label>
<input type="file" name="fileupload" id="fileupload" class="form-control" />
</div>
<div class="form-group">
<input type="button" name="save" id="save" value="Save" class="btn btn-info mt-3" />
</div>
</form>
........................................
.......................................
<script src="js/jquery.min.js"></script>
<script>
$(document).ready( function () {
$("#save").click(function(){
const fileupload = $('#fileupload').prop('files')[0];
let formData = new FormData();
formData.append('fileupload', fileupload);
formData.append('name', $('#name').val());
formData.append('address', $('#address').val());
$.ajax({
type: 'POST',
url: "upload.php",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (msg) {
alert(msg);
document.getElementById("form-data").reset();
},
error: function () {
alert("Upload Error!");
}
});
});
});
</script>
How to solve this problem?
question from:
https://stackoverflow.com/questions/65559722/different-image-upload-form-in-one-page 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…