I have created a profile form for users to update their information. Within this form, the user should be able to update their profile picture. However, at this point in time, it is making me update the picture each time or the image (name) is removed from the DB. I would like to have it set up to where if the user does not update the photo the old image that is already set in the DB is used.
Code has not been refactored.
I have tried several approaches to get this to work. I have attempted to use if(isset($_FILES['profile_image']))
, I have tried other if statements with no success.
I did not add all of the code to try to keep it cleaner for you. I apologize if I have left anything out.
PHP
if(isset($_POST['update_profile'])){
if(isset($_FILES['profile_image']['name'])){
$profile_image_temp = $_FILES['profile_image']['tmp_name'];
$profile_image = $_FILES['profile_image']['name'];
move_uploaded_file($profile_image_temp,
"../includes/profile_images/$profile_image");
} elseif (!isset($_FILES['profile_image']['name'])){
$query = "SELECT * FROM profiles WHERE profile_id = $profile_id";
$complete_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($complete_query)){
$profile_image = $row['profile_image'];
}
}
$update_profile = "UPDATE profiles SET profile_image = '{$profile_image}'
WHERE profile_id = $profile_id";
HTML
<div class="contact-clean col-md-5" style="margin:0 auto; padding-top:
50px;">
<h2 class="text-center">Update Profile</h2>
<p class="text-center"><small>Fields with an asterisk are required
</small></p>
<form method="post" action="#" enctype="multipart/form-data">
<div class="form-group">
<label for="profile_image">Profile Image * </label><input class="form-
control" type="file" name="profile_image" id="profile_image" value="<?php
echo $profile_image ?>">
</div>
<button style="margin-top: 20px; margin-bottom: 300px;"" class="btn btn-
primary btn-lg" type="submit" name="update_profile"
id="update_profile">Update Profile</button>
</form>
</div>
Expected: If the user does not add an image their old image will still be there for them to use.
Actual Results: If the user does not add an image during the update the image is removed from the DB.