如何只允许每个IP两个帐户?

时间:2013-01-08 11:14:15

标签: php pdo count

我正在尝试阻止来自同一IP的多个帐户:

if (! empty($_SERVER['HTTP_CLIENT_IP']))
{
    $ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $ip = $_SERVER['REMOTE_ADDR'];
}

$stmt = $db->prepare("SELECT 1 FROM users WHERE ip = :ip");
$stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
$result = $stmt->execute();
$row = $stmt->fetch();

if ($row)
{
    die("Only one account per IP is allowed !");
}

这有效,但如果我想为每个IP允许两个帐户怎么办?我试过了:

$stmt = $db->prepare("SELECT * FROM users WHERE ip = :ip");
$stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
$result = $stmt->execute();
$row = $stmt->fetch();

if ($row > 1)
{
    die("Only one account per IP is allowed !");
}

不起作用。第二个帐户是不允许的。

2 个答案:

答案 0 :(得分:2)

你需要数数吧。使用count()  

SELECT count(*) as count FROM users WHERE ip = :ip

http://php.net/manual/en/pdostatement.rowcount.php

答案 1 :(得分:1)

只需更新下面的查询:

$stmt = $db->prepare("SELECT count(*) FROM users WHERE ip = :ip");