Why does this mysqli_fetch_assoc return null?

Asked

Viewed 32 times

0

When I run the code below, when I reach the line $user_image = $row['user_image'];, the variable $row is set to null and the loop is terminated, however, if I remove Else the code runs normally and the variable $user_image receives the data from the database. Why this happens?

    $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 in which 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 the function move_uploaded_file 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.

  • You use the variable $row after that code?

  • @Andersoncarloswoss No, only in this passage.

  • @Andersoncarloswoss PHP version: 7.0.10

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.