I'm working on a file upload application. Every file is uploaded into the website's /files/
directory, so not directly into the database. I've been trying it with images.
The thing is, I also want to use a database to show every picture uploaded, together with some more information... and also to check if a file with the same name already exists.
What the user needs to do: Select a file he wants to upload, using a file
input type.
What the application does: Firstly, it checks in the database if the file name was already used. If not, it proceeds to uploading the picture using $_FILES
and moving it into the /files/
folder, using the move_uploaded_file()
function. Then, it creates a line in the database table, that contains the file's category (fcategory
-> "Picture"), the file name (fname
), its font-awesome icon (ficon
), a description (fdesc
) and a link (flink
) that is based on /files/$_FILES['name']
.
This is my form:
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" class="btn" name="btn">
</form>
and this is the PHP code:
<?php
if (isset($_POST['btn']))
{
$file = $_FILES['file'];
$stmt = $conn->prepare("SELECT * FROM files WHERE fname = ?");
$stmt->bind_param("s", $file['name']);
$stmt->execute();
$res = $stmt->get_result();
$num = $res->num_rows;
if ($num == 0) {
move_uploaded_file($file['tmp_name'], "files/".$file['name']);
echo "<br><br>Image was uploaded.";
$stmt2 = $conn->prepare("INSERT INTO files (fcategory, fname, ficon, fdesc, flink) VALUES (?, ?, ?, ?, ?)");
$name = $file['name'];
$link = "https://LINKTOWEBSITE.COM/files/".$name;
$stmt2->bind_param("sssss", "Imagine", $name, "fa-image", "No description.", $link);
$stmt2->execute();
$stmt2->close();
$stmt->close();
}
else
{
echo "<br><br>Choose another name for the image.";
$stmt->close();
}
}
?>
I decided not to provide the link to my website. That's why I replaced it with LINKTOWEBSITE.COM
The problem is, data isn't inserted into the database, but the file is inserted into the /files
folder.
Could it be because I'm using two prepared statements, nested one into another? The first statement, the one that checks for an already existing file, works perfectly. What can I do?
If you need more information, just leave a comment and I'll edit the question as soon as possible. Thank you so much!