How should I properly store and retrieve IPs?

本秂侑毒 提交于 2019-12-25 01:55:09

问题


I have table Users with one column user of type VARCHAR(15). I can insert a period into it:

INSERT INTO `LJ`.`Users` (`user`) VALUES ('.')

Now I want to search for this period:

SELECT * FROM `Users` WHERE `user` LIKE '.'

or

SELECT * FROM `Users` WHERE `user` = '.'

In both cases, the existing entry is not found:

MySQL returned an empty result set (i.e. zero rows). (Query took 0.0001 sec)

The same problem with the comma.

Actually, my intention is to store IP addresses like 125.50.75.80, but I've boiled the problem down to inability to search for a punctuation sign. I tried '\.' also to no avail.

And this is a problem with literals; what to do with variables, containing strings with periods?

UPDATE: I've tested in a database created in the command line with table:

CREATE TABLE LJ.Users ( user VARCHAR(15) );

and everything works OK. I suspect something is wrong in my database created with phpMyAdmin:


回答1:


The current issue with your VARCHAR column is the collate type you're using armscii8_general_ci which converts some of the stored characters such as comma and dot.

See example here.

Perhaps you meant to use utf8_general_ci which would yield your desired results:

See example here.


Do not use VARCHAR to store IPv4, use INT unsigned and then you can use INET_ATON() and INET_NTOA() functions to return/insert/compare the IPv4.

CREATE TABLE users
(
    user_ip INT unsigned
);

Then to insert an IPv4 you would use:

INSERT INTO users (user_ip) VALUES (INET_ATON('125.50.75.80'));

Then you could read it like this:

SELECT INET_NTOA(user_ip) FROM users WHERE user_ip = INET_ATON('125.50.75.80')

Live DEMO.



来源:https://stackoverflow.com/questions/26266994/how-should-i-properly-store-and-retrieve-ips

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!