Trying to get property of non-object

前端 未结 2 1513
执念已碎
执念已碎 2021-01-21 11:39

This script works great. I call it in top of my scripts. But if a user that is NOT banned enters the site they get:

Notice: Trying to get property of non-object          


        
相关标签:
2条回答
  • 2021-01-21 12:08

    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>");
    
        }
    }
    
    0 讨论(0)
  • 2021-01-21 12:13

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

    0 讨论(0)
提交回复
热议问题