The problem is that you store the IP number as a string.
When you ORDER BY it in SQL, it is ordered alphabetically.
And looking from an alphabetical angle, 4 is less than 12, simply because the string is shorter.
As the other repliers mentioned there are several ways to overcome this by making your method of ordering fit your data or making your data fit the ordering method.
If you want to continue storing the IP as a string, you will have to
prepend leading zeros to each part of the IP so it looks like this:
020.145.002.023
And why? because now all strings have the same length. The only thing left to order by is content, and even in strings 1 is less than 2.
You could do this with a complex SQL query (mysql has very nice lpad() and substring_index() functions that make this "simple")
Or you could do it in PHP by exploding the IP and prepending zeroes.
My recommended course of action would be to transform the already stored IP's to "normalized" IPs (with leading zeroes) and
from then on store all new IP's in the same way.
In php you can easily explode() an IP into 4 strings, which in MySQL you can lpad() and concat() back into one string for storage.
If you are free to change the layout of your database you
have a few other options to play with:
- Store the IP as one large number.
- Store each segment of the IP seperately.
The first is best because the seconds eats space like there's no tomorrow :-)
An IP is basically a number that is chopped into pieces, each piece having 256 possible values.
To get one big value just make a calculation like this:
IP=1.2.3.4
number=(1256256256)+(2256256)+(3256)+4
Getting the original IP back is a bit more difficult, but there lies your challenge.
You could ofcourse choose to store both the string and the value, so you can order by the value and still display the string.