好的,我有一个Minecraft服务器,我正在为它制作一个投票脚本。
我需要一种方法来检查mySQL中的用户ip。 如果它不存在,它会将ip放入数据库中,并在数据库中24小时后将其删除。
如果有人能帮助我这样做,那就太好了,谢谢
答案 0 :(得分:1)
有很多关于如何实现这一目标的在线教程,因此我不会给你代码。只是提示你一些提示。
在PHP中,您可以从$_SERVER
超全局
$ip = $_SERVER['REMOTE_ADDR'];
检查表格中是否存在
$query = sprintf("SELECT COUNT(*) FROM yourtable WHERE `ip` = '%s'", mysql_real_escape_string($ip));
如果它不存在,请使用INSERT
命令和时间戳存储它。
对于24小时后删除,您可以设置每小时左右运行一次的cron作业,并删除所有已过期的条目。但是,不删除条目会更容易。相反,当用户投票时,只需检查他上次投票的时间戳。如果自上次投票后已经过了24小时,只需更新时间戳。
基本上,工作流程将是:
1. Get users's IP address.
2. Does this IP exist in table?
2a. If no, let user vote, and enter his ip in the table along with the current time in the timestamp column
2b. If yes, get the timestamp of his last vote. Has it been 24 hours since his last vote?
2b.a. If yes, let user vote and update timestamp column with current time.
2b.b. If no, do not let user vote / reject his vote. Leave timestamp column unchanged.
答案 1 :(得分:0)
最简单的方法是执行以下操作
$ip = $_SERVER['REMOTE_ADDR'];
// Run cleanup for given IP
$result = mysql_query("SELECT * FROM table
WHERE `ip`='$ip' AND `timestamp` > NOW() - 24*3600");
if (mysql_num_rows($result)==0)
// there is no record within the last 24h, let insert a new one
{
mysql_query("INSERT INTO table SET `ip`='$ip', `timestamp` = NOW()");
echo "Thank you for your vote!";
}
else echo "You may vote only once in 24 hours";
// run total cleanup query from time to time
if (rand(1,5)<2) mysql_query("DELETE FROM table
WHERE `timestamp` < NOW() - 24*3600");
ps:如果你有不同的投票,每个投票应该有不同的唯一ID。例如,在两列ip
和timestamp
之前的MySQL表应该还有一列voteid
。在这种情况下,上面的代码将更改为
// voteid should be somehow set to the id of the voting.
// for example by GET request
$voteid = intval($_GET['voteid']);
$ip = $_SERVER['REMOTE_ADDR'];
// Run cleanup for given IP
$result = mysql_query("SELECT * FROM table
WHERE `ip`='$ip' AND `voteid`='$voteid` AND `timestamp` > NOW() - 24*3600");
if (mysql_num_rows($result)==0)
// there is no record within the last 24h, let insert a new one
{
mysql_query("INSERT INTO table SET `ip`='$ip',
`voteid`='$voteid', `timestamp` = NOW()");
echo "Thank you for your vote!";
}
else echo "You may vote only once in 24 hours";
// run total cleanup query from time to time
if (rand(1,5)<2) mysql_query("DELETE FROM table
WHERE `timestamp` < NOW() - 24*3600");