How do I use the file name in the database to retrieve the corresponding file in a folder on the server?
Currently I have a comment section that is working but not sure how to retrieve the image that corresponds with the comment.
MY DATABASE: comments
STRUCTURE: cid A_I Primary uid varchar(128) date datetime message text iamges varchar(50)
HTML:
<?php
echo "<form method='POST' enctype='multipart/form-data' action='".setComments($conn)."'><br>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
Select a file:<br><input type='file' name='image' id='image'><br<br><br>
Comment:<br> <textarea name='message'></textarea><br><br>
<button type='submit' name='commentSubmit'>Upload</button><br><br><br>
</form>";
getComments($conn);
?>
FUNCTIONS:
<?php
function setComments($conn) {
if (isset ($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$file_name = $_FILES['image']['name'];
$sql = "INSERT INTO comments (uid, date, message, images) values ('$uid','$date','$message','$file_name')";
$result = mysqli_query($conn, $sql);
}
}
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png"."gif");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG, GIF, or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Successfully uploaded file!";
}else{
print_r($errors);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments ORDER BY date DESC LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
echo $row['uid']."<br>";
echo $row['date']."<br><br>";
echo $row['message']."<br><br>";
}
}