PHP Help needed (inserting an IP block into a MySQL database)

KuJoe

Well-Known Member
Verified Provider
So I'm working on our SolusVM replacement and am hitting my head trying to figure out how to handle inserting hundreds of IPs at a time into a MySQL database. The field is varchar(30) and I was thinking of something like this (found the code while searching around):


$main = $_POST["ip"];
foreach(range(1, 254) as $ip) {
$adr = $main . $ip;
}

Any comments or suggestions for this? I was hoping to use a form to use a range of IPs (starting IP - ending IP) or use slash notation so certain size blocks would be added (/24, /27, /22, etc...) but code to add a /24 (254 IPs) would work just fine also. Keep in mind this is only for IPv4 for now.
 
Last edited by a moderator:

Damian

New Member
Verified Provider
Clunky as it is, that would probably be the best method. Another method is the first answer on http://stackoverflow.com/questions/1938162/how-to-create-a-range-of-ip-addresses

Keep in mind that you can concatenate values together for your INSERT statement, and therefore do a single INSERT statement instead of 255 INSERT statements for each IP. Like:

INSERT INTO ipv4_table (ip) VALUES ("192.168.0.1"), ("192.168.0.2"), ("192.168.0.3"),("192.168.0.4") etc

This can be effected like: 


$main = $_POST["ip"];
$insertPrefix = "INSERT INTO ipv4_table (ip) VALUES ";
foreach(range(1, 254) as $ip) {
$adr = $main . $ip;

$insertPrefix .= "(" . $adr . "),";

}
You might have to clean up the tailing comma.
 
Last edited by a moderator:

Damian

New Member
Verified Provider
I found this in my pile of code snippets:


$range = "192.168.0.0/24";
function ipListFromRange($range){
$parts = explode('/',$range);
$exponent = 32-$parts[1].'-';
$count = pow(2,$exponent);
$start = ip2long($parts[0]);
$end = $start+$count;
return array_map('long2ip', range($start, $end) );
}

Should return an array of every IP for the given range. I'm not sure where I found it, so I don't know if anyone's updated it.
 

Damian

New Member
Verified Provider
And one more bit of info: a varchar(15) should be sufficient to hold the max address length, xxx.xxx.xxx.xxx. Not that 15 extra bytes is going to make a difference :p
 

KuJoe

Well-Known Member
Verified Provider
And one more bit of info: a varchar(15) should be sufficient to hold the max address length, xxx.xxx.xxx.xxx. Not that 15 extra bytes is going to make a difference :p
I'm keeping the tables exactly as SolusVM has them to make importing easier. Once I have everything moved over I can do manual cleanup on the database but for now I just want to export tables X, Y, and Z then import them into the new database.
 
Last edited by a moderator:
Top