mysqli_fetch_array($ result,MYSQLI_NUM);

This mysqli_fetch_array not returning values. Checked it for SQL errors, none found. some error in PHP or functions I guess. Please help me correct it.

$login = login($username, $password);
if ($login == false) {
    $errors[] = "That username and password     combination is incorrect";
}

// validate login
function login($username, $password){
    $user_id = id_from_username($username);
    echo $user_id;
    $password = md5($password);
    $username = sanitize($username);
    $query = "SELECT `password` FROM `user_data` WHERE `username` = '$username' ";
    $result = mysqli_query($conn,$query);
    $row = mysqli_fetch_array($result, MYSQLI_NUM);

    if ($row[0] == $password) {
        echo "Login successful";
        return $user_id;
    }
    else{
        echo "Login not successful";
        return false;
    }
}

// user id from username
function id_from_username($username){
    $username = sanitize($username);
    $query = "SELECT `user_id` FROM `user_data` WHERE      `username` = '$username'";
    $result = mysqli_query($conn,$query);
    $row = mysqli_fetch_array($result, MYSQLI_NUM);
    return $row[0];
}

EDIT: As Lawrence correctly pointed out I missed the variable scope issue. mysqli_query does not have access to $conn variable.


Try to check the number of returned rows in the $result:

echo $result->num_rows;

Or print it to the log if you have some. Not sure how you are checking mysqli_fetch_array does not return values - try var_dump() or print_r().

Few further recommendations:

  • Both queries in your question select from the same table - user_data - it is pretty inefficient to do it separately (unless id_from_username is commonly used elsewhere), I'd merge that into one query to select it at once:

    SELECT user_id, password FROM user_data WHERE ...

  • Using mysqli_query and concatenating user input into the query is usually a bad idea. Not sure what your sanitize function does but I'd still use variable binding instead, even mysqli supports that with mysqli_prepare, see here.

  • Based on your code you are storing passwords in database using md5. This is a very bad practice. PHP provides very nice functions password_hash and password_verify since PHP 5.5.0, they will handle password hashing for you and make your application a lot more secure.