-1

I am a beginner to PHP. I am trying to insert large amount of items into database. I am using for loop and mysqli_query commands.

My pseudo-code is something like this:

for ($i=0; $i<50000; $i++) {
  mysqli_query($con, "INSERT INTO users (name, age) VALUES ('$name','$age'); ") ;

}

I have my code working a few hundred loops and then poof: Fatal error: Maximum execution time of 30 seconds exceeded in xxx on line xxx

For me, only solution is to manually increment my counter every time after loop breaks.

Is there any other solution? Please, help!

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76

3 Answers3

5

Don't do a query for every record one-at-time. You can do multiple inserts with one statement. The example below does 50 at one time. You can probably safely increase that to 100 or even 500.

$counter = 0;
$query = 'INSERT INTO users (name, age) VALUES ';
for ($i=0; $i<50000; $i++) {
  $counter++;
  $sql .= "('$name','$age'),"; 
  // execute query every 50 records
  if ($counter % 50 === 0) {
      $sql = rtrim($sql, ',');
      mysqli_query($con, $query . $sql) ;
      $sql = '';
  }
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

Throw a try catch

for ($i=0; $i<50000; $i++) {
  try {
    mysqli_query($con, "INSERT INTO users (name, age) VALUES ('$name','$age'); ") ;
  } catch ($e) {
    // You can log $e here if you want
    // It would also probably be good to print out your query 
    // so you can go back and try it again later
  }

}
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
0

The most helpful answer was the comment from Jay Blanchard:

Try the set_time_limit() function. Calling set_time_limit(0) will remove any time limits for execution of the script.

I have inserted set_time_limit(0) at the beginning of the page, and my PHP script now works perfectly!

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76