Reputation: 3036
I am trying to inert about ~1000 records in into MySQL. But my attempt below only 'inserts' on the first query. After that I gets the 'or die' error message. I tried changing the if statement to random numbers (other then five), but it always dies after the first insert. What am I doing wrong?
$i=0;
foreach(.....){
if($>5){
insert($name, $phone);
}
}
function insert($n, $p){
$dbhost = "---";
$dbuser = "---";
$dbpass = "---";
$dbname = "---";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
mysql_select_db($dbname);
$query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
mysql_query($query) or die('Error, query failed');
mysql_close();
}
Upvotes: 1
Views: 224
Reputation: 44373
This is your code
$i=0;
foreach(.....){
if($>5){
insert($name, $phone);
}
}
function insert($n, $p){
$dbhost = "---";
$dbuser = "---";
$dbpass = "---";
$dbname = "---";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
mysql_select_db($dbname);
$query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
mysql_query($query) or die('Error, query failed');
mysql_close();
}
Connecting to MySQL just to insert one row followed by disconnecting and reconnecting is a VERY EXPENSIVE OPERATION !!!
Try reorganizing it like this :
$dbhost = "---";
$dbuser = "---";
$dbpass = "---";
$dbname = "---";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
mysql_select_db($dbname);
$i=0;
foreach(.....){
if($>5){
insert($name, $phone);
}
}
mysql_close();
function insert($n, $p){
$query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
mysql_query($query) or die('Error, query failed');
}
Upvotes: 3