I am having difficulty removing an image URL from a MySQL table with the use of a checkbox, if a user decides they no longer want an image (avatar) to be used on their profile.
The table (it has more columns) looks like:
user_id | img | user_name
1 | http://www.domain.com/path/to/image | User A
2 | | User B
3 | | User C
On the user profiles, if a URL exists in img, then the image properly shows.
My HTML form looks like:
<form method="post" action="user/update_info.php">
<div class="form-group">
<label for="user_name">Username:</label>
<input type="text" id="user_name" name="user_name" value="user_name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="password" required>
</div>
<div class="form-group col-sm-4">
<input type="file" name="img">
<br>
<label for="noav">Use no avatar.</label>
<input type="checkbox" id="noav" name="noav" value="Yes">
</div>
<input type="submit" class="btn btn-warning" value="Update">
</form>
My PHP file looks like:
<?php
$user_id = $_SESSION["user"]['user_id'];
$user_name = $_POST['user_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$noav = $_POST['noav'];
$session_password = $_SESSION["user"]['password'];
if ($password != $session_password) {
$password = password_hash($password, PASSWORD_DEFAULT);
}
$img = $_FILES["img"];
$query = "UPDATE users
SET user_name='$user_name', char_name='$char_name',
user_email='$email', password='$password'
WHERE user_id=$user_id";
mysqli_query($this->connection, $query)
or die("Update error: " . mysqli_error($this->connection));
if($img["error"] == 0) {
$name = "public/gallery/" . time() . $img["name"];
$name_in_db = URL . $name;
$tmp_name = $img["tmp_name"];
move_uploaded_file($tmp_name, $name);
if ($noav = 'Yes') {
$query = "UPDATE users SET img='' WHERE user_id=$user_id";
} else {
$query = "UPDATE users SET img='$name_in_db' WHERE user_id=$user_id";
}
mysqli_query($this->connection, $query)
or die("Update error: " . mysqli_error($this->connection));
}
?>
Before I added in the "noav" checkbox, variable, and if check (only the bottom query existed), everything functioned properly.
Adding in the "noav" stuff essentially broke it. Now, no matter what, if the checkbox is checked or not, and if an image is selected or not, it clears the img column for that user, making no img whatsoever.