未定义的变量,为什么?

时间:2014-04-16 17:09:36

标签: php undefined

我不明白为什么变量$ return和$ id未定义...

错误:

Notice: Undefined index: id in C:\inetpub\wwwroot\inc\classes\users.php on line 49

Notice: Undefined variable: return in C:\inetpub\wwwroot\inc\classes\users.php on line 49

代码:

public static function getFollowers($id)
{
    $query = db::query('SELECT id_follower FROM '.TABLE_FOLLOWERS.' WHERE id_user = "'.db::escape($id).'"');
    while($array = db::fetch_assoc($query))
    {
        $return .= '<img style="margin-left: 2px;" id="img-round" src="'.users::userAvatar($array['id']).'" width="40" height="40" />';
    }
            return $return;
}
第49行:

            $return .= '<img style="margin-left: 2px;" id="img-round" src="'.users::userAvatar($array['id']).'" width="40" height="40" />';

感谢。

1 个答案:

答案 0 :(得分:1)

要解决第二个问题,首先在连接变量之前启动变量:

public static function getFollowers($id)
{
    $return = ''; /* HERE */
    $query = db::query('SELECT id_follower FROM '.TABLE_FOLLOWERS.' WHERE id_user = "'.db::escape($id).'"');
    while($array = db::fetch_assoc($query))
    {
        $return .= '<img style="margin-left: 2px;" id="img-round" src="'.users::userAvatar($array['id']).'" width="40" height="40" />';
        /* return $return; -- move this outside the while() loop */
    }
    return $return; /* MOVED HERE */
}

要解决第一个问题,$array没有id的密钥对。在尝试使用它之前验证它是否存在:

    if ( isset( $array['id'] ) ) $return .= '<img style="margin-left: 2px;" id="img-round" src="'.users::userAvatar($array['id']).'" width="40" height="40" />';

正如评论中所述,当您可能希望访问$array['id']

时,您正试图访问$array['id_follower']