简体   繁体   English

如果数据库中已经有IP地址,则很简单

[英]Simple if IP address is already in the database

Hey I want to do a simple check when I'm inserting an impression into a database. 嘿,当我将印象插入数据库时​​,我想做一个简单的检查。 I only want to determine if the IP address is already in the database ip field. 我只想确定IP地址是否已经在数据库ip字段中。

In PHP preferably, instead of the the query. 最好用PHP,而不是查询。

You can convert the IP adress to an integer using ip2long or the corresponding mysql function. 您可以使用ip2long或相应的mysql函数将IP地址转换为整数。 Then I suggest a table with MyIsam storage engine and a hash index. 然后,我建议使用MyIsam存储引擎和哈希索引的表。 If you wan't to be ready for ipv6 you can stoer binary data. 如果您不想为ipv6做好准备,则可以存储二进制数据。 If possible you can also do this in memory tables or apc cache (when you don't need the ip adresses to be stored forever and they can be lost on a server restart). 如果可能的话,您也可以在内存表或apc高速缓存中执行此操作(当您不需要永久存储ip地址时,它们可能会在服务器重启时丢失)。

$check_ip = (mysql_num_rows(mysql_query("SELECT ip FROM ip_table WHERE ip='$ip'",$db)) > 0) ? true : false;

You're likely to need to use MySQL to determine this (how would PHP know unless it was maintaining its own set of all "known" IP addresses outside of the database?) 您可能需要使用MySQL来确定这一点(PHP除非在数据库外部维护自己的所有“已知” IP地址集,否则如何知道?)

You could however, potentially use a single query, most likely via the use of an INSERT ... ON DUPLICATE KEY UPDATE style query. 但是,您可能会使用单个查询,很可能是通过使用INSERT ... ON DUPLICATE KEY UPDATE样式查询。

ie: You'd try the insert anyway, but if there was a duplicate key you'd instead update a view counter, etc. as required. 即:无论如何,您都尝试插入,但是如果有重复的键,则可以根据需要更新视图计数器等。

That said, it's pretty naive to presume that an IP address is unique in any meaningful way, as proxy servers, etc. will effectively hide many users behind a single IP address. 就是说,假定IP地址以任何有意义的方式都是唯一的,这很天真,因为代理服务器等将有效地将许多用户隐藏在一个IP地址后面。 Then again, this may not be relevant within your problem domain. 再说一遍,这可能与您的问题域无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM