When I run the code below, when I reach the line $user_image = $row['user_image'];
, the variable $row
is assigned as null and the loop is terminated, however, if I remove the else the code is executed normally and the variable co_de % receives the data from the database. Why does this happen?
$user_image= $_FILES['image']['name'];
$user_image_tmp = $_FILES['image']['tmp_name'];
if(empty($user_image)){
$query = "SELECT * FROM users WHERE user_id = {$user_id}";
$search_image = mysqli_query($connection, $query);
if (!$search_image) {
die("Error: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_assoc($search_image)) {
$user_image = $row['user_image'];
}
} else {
move_uploaded_file($user_image_tmp, "../users-images/" . $user_image);
}
Code where the assignment works correctly:
$user_image= $_FILES['image']['name'];
$user_image_tmp = $_FILES['image']['tmp_name'];
move_uploaded_file($user_image_tmp, "../users-images/" . $user_image);
if(empty($user_image)){
$query = "SELECT * FROM users WHERE user_id = {$user_id}";
$search_image = mysqli_query($connection, $query);
if (!$search_image) {
die("Error: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_assoc($search_image)) {
$user_image = $row['user_image'];
}
}
Note: I know that the $user_image
function returns false if the file is not valid and I can remove this else from the code, my intention with the question is to understand why this behavior happens.