试图获得非对象的属性

时间:2010-07-22 00:23:14

标签: php

这个脚本效果很好。我把它称为我的脚本之上。但是,如果未被禁止的用户进入该网站,他们会得到:

Notice: Trying to get property of non-object in index.php on line 20

功能:

// Check if conecting user is banned. If ban has expired delete row.
function check_bans()
{

// IP address
$user_ip = $_SERVER['REMOTE_ADDR'];

$query = mysql_query("SELECT ip, expire FROM bans WHERE ip = '$user_ip'");
$row = mysql_fetch_object($query);

$expire = $row->expire ? date('M d Y H:i', $row->expire) : 'Never';

// Did we find a match?
if (mysql_num_rows($query)) {

    // Has this ban expired? Then delete and let user inside.
    if ($row->expire != '' && $row->expire <= time())
        mysql_query("DELETE FROM bans WHERE ip = '$user_ip'") or die (mysql_error());
    else
        die("<h1 align=\"center\" style=\"color:maroon\">You have been IP banished. Ban will be lifted: $expire</h1>");

}

}

2 个答案:

答案 0 :(得分:4)

因为如果用户未被禁止,则查询结果为零,$row作业gets assigned false对象)。因此,发生该错误是因为您试图在布尔值上调用方法。尝试:

function check_bans() {

    // IP address
    $user_ip = $_SERVER['REMOTE_ADDR'];

    $query = mysql_query("SELECT ip, expire FROM bans WHERE ip = '$user_ip'");
    $row = mysql_fetch_object($query);
    if($row) {

        $expire = $row->expire ? date('M d Y H:i', $row->expire) : 'Never';

        // Has this ban expired? Then delete and let user inside.
        if ($row->expire != '' && $row->expire <= time())
            mysql_query("DELETE FROM bans WHERE ip = '$user_ip'") or die (mysql_error());
        else
            die("<h1 align=\"center\" style=\"color:maroon\">You have been IP banished. Ban will be lifted: $expire</h1>");

    }
}

答案 1 :(得分:0)

如果没有匹配的行,则$row将为FALSE。您应该在if ($row)之后的所有内容周围添加mysql_fetch_object