Jump to content

Recommend approach to insert multiple MySQL records with PHP


Recommended Posts

Normally, I use PDO and make a separate query for each insert.  Started thinking maybe it would be best to insert all records with one query.  Any advise?  Thank you

<?php
$insert=array(4,3,6,9,6,3,6);
$stmt = $conn->prepare('INSERT INTO myTable(a,b,c,d,e,f) VALUES (?,"foo","bar",NOW(),FALSE,TRUE)');
foreach($insert as $id) {
    $stmt->execute(array($id));    
}
?>  

<?php
$insert=array(4,3,6,9,6,3,6);
$sql = 'INSERT INTO myTable(a,b,c,d,e,f) VALUES ';
foreach($insert as $dummy) {
    $sql.='(?,"foo","bar",NOW(),FALSE,TRUE),';
}
$sql=rtrim($sql,',');
$stmt = $conn->prepare($sql);
$stmt->execute($insert);  
?>
Link to comment
Share on other sites

Thanks Barand,  When using the later approach, know how big the query could get before MySQL chokes?

 

Impossible to state. There are many variable to consider other than just the number of records being added: CPU, Memory, how big the existing database is, are there any triggers, complexity of the table, the type of data for those records, shared server, etc., etc.

 

The only way to know is to run some tests using the same or similar hardware and configuration as you would expect to see in your production environment. If this is a shared server, you are really at a disadvantage as your results would be based on what is happening with the other sites using that same database server.

Link to comment
Share on other sites

 

I was thinking of the more general case

$sql.='(?, ?, ?, NOW(), ?, ?),';

 

 

Please elaborate.  How would this work?  My approach would just do the following:

$sql='INSERT INTO myTable
   (a,b,c,d,e,f)
VALUES
   (?,"foo","bar",NOW(),FALSE,TRUE),
   (?,"foo","bar",NOW(),FALSE,TRUE),
   (?,"foo","bar",NOW(),FALSE,TRUE),
   (?,"foo","bar",NOW(),FALSE,TRUE),
   (?,"foo","bar",NOW(),FALSE,TRUE),
   (?,"foo","bar",NOW(),FALSE,TRUE)';

$stmt = $conn->prepare($sql);

$stmt->execute(array(4,3,6,9,6,3,6)); 
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.