Check if ip is already registered in the database

Asked

Viewed 35 times

-3

The code lowers checks if the user’s ip is already registered in the database, but it keeps sending the information that the ip is free, even though it is already registered in the database.

   $ip = $_SERVER["REMOTE_ADDR"];

    $query = mysql_query("SELECT ip FROM emails WHERE ip = '$ip'");
    $countUser = mysql_num_rows($query);

    if($countUser > 0){
      while($row = mysql_fetch_array($query)){
        echo "IP já registrado";
      }
    } else {
      echo "IP livre";
    }

1 answer

1


I don’t know what version of your PHP, but in the version I use (version 7) this code of yours does not work.

If you consult the manual, you will have

Warning This extension has been deprecated since PHP 5.5.0 and has been removed in PHP 7.0.0. Use Mysqli or Pdo_mysql alternatively.



In PHP 7, it works like this:

$con = mysqli_connect("host","user","pass","dbname");

if(!$con) {
    echo "Erro: falha ao se conectar com o banco <br>";
    echo "Errno: " . mysqli_connect_errno() . PHP_EOL;
}

$ip = $_SERVER["REMOTE_ADDR"];
$query = mysqli_query($con, "SELECT `ip` FROM `emails` WHERE `ip` = '$ip'");
$countUser = mysqli_num_rows($query);

if($countUser > 0){
  while($row = mysqli_fetch_array($query)){
    echo "IP já registrado";
  }
} else {
  echo "IP livre";
}

mysqli_close($con);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.