phpmysqli

How to limit the number of visits from a given IP?


This is how I'm going to find out whether the user's ip exists in the database more than 5 times.

if ($stmt = $this->mysqli->prepare('SELECT iplukket FROM opgaveip'))
    { 
        $stmt->bind_param('s', $iplukket);
        $iplukket = $_SERVER["REMOTE_ADDR"];
        $stmt->execute();
        $stmt->bind_result($iplukket);
        while ($stmt->fetch()) {
            if($iplukket < 5)
            {
                echo "NOW!";
            }
            elseif($iplukket > 5)
            {
                echo "Error";   
            }
        }
        $stmt->close();
    } else {
        echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
    }

But it doesn't show NOW! or error. What could be the problem?


Solution

  • You should use count

    if ($stmt = $this->mysqli->prepare('SELECT iplukket FROM opgaveip'))
    

    should be

    if ($stmt = $this->mysqli->prepare('SELECT COUNT(iplukket) iplukket FROM opgaveip'))
    

    Also you should have where condition in the query or it will return count of all the rows in the database

    Basically your select statement should be like

    SELECT COUNT(ipcolumnname) ipcolumnname FROM opgaveip WHERE ipcolumnname=iplukket
    

    and you should bind check for ipcolumnname>5 in the result.