开发者

Trying to get property of non-object

开发者 https://www.devze.com 2023-01-08 02:59 出处:网络
This script works great. I call it in t开发者_高级运维op of my scripts. But if a user that is NOT banned enters the site they get:

This script works great. I call it in t开发者_高级运维op of my scripts. But if a user that is NOT banned enters the site they get:

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

The function:

// 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>");

}

}


Because if the user has not been banned, the query yields zero results and the $row assignment gets assigned false (and not an object). So, that error happens because you're attempting to call a method on a boolean. Try:

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>");

    }
}


If there is no matching row, then $row will be FALSE. You should add if ($row) around everything after mysql_fetch_object.

0

精彩评论

暂无评论...
验证码 换一张
取 消