开发者

Simple if IP address is already in the database

He开发者_如何学Pythony 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.

In PHP preferably, instead of the the query.


You can convert the IP adress to an integer using ip2long or the corresponding mysql function. Then I suggest a table with MyIsam storage engine and a hash index. If you wan't to be ready for ipv6 you can stoer binary data. 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).


$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?)

You could however, potentially use a single query, most likely via the use of an INSERT ... ON DUPLICATE KEY UPDATE style query.

i.e.: 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. Then again, this may not be relevant within your problem domain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜