I am trying to upload an image to my server and save its name and path into my database. Uploading the file to my server works, saving the data in the database does not.
images table
image_id int(11)
image_name varchar(64)
image_path varchar(64)
Upload script
// Upload image to the server
$target_dir = "./path/to/image/folder/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "Die Datei ist keine Bilddatei.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Bitte nenne die Datei um, diese Datei existiert bereits.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Diese Datei ist größer als 5MB und kann daher nicht hochgeladen werden.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Ausschließlich JPG, JPEG, PNG & GIF Dateien können hochgeladen werden.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Ein Fehler ist aufgetreten. Die Datei konnte nicht hochgeladen werden.";
// if everything is ok, try to upload file
} else {
========================= DATABASE PART ========================
// create a database connection
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// prepare and bind
$stmt = $conn->prepare("INSERT INTO images (image_id, image_name, image_path) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $image_id, $image_name, $image_path);
// set parameters and execute
$image_id = '';
$image_name = $target_file;
$image_path = $target_dir;
$stmt->execute();
$stmt->close();
$conn->close();
==================================================================
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
header("Location:http://homepage.com");
} else {
echo "Während des Hochladens der Bilddatei ist ein Fehler aufgetreten. Bitte versuche es erneut.";
}
}
The file is uploaded exactly as it should be.
The database stays empty without an error message.
var_dump on $image_name
and $image_path
return the correct values.
What am I missing?
I would be very thankful for any kind of help. Thank you!