Jump to content

[SOLVED] Which insert method is better


HuggieBear

Recommended Posts

I have about 150 rows that I'm inserting into my database.

 

Is it better to loop through the data doing a mysql_query() for each insert, or loop through the data creating a sql statement with a single insert.  See below for example:

 

<?php
// Multiple inserts in a loop
foreach ($row as $k => $v){
   $sql = "INSERT INTO table_name VALUES ($row[$k], $row[$k])";
   mysql_query($sql, $db);
}
?>

 

or

 

<?php
// Single insert after creating a string in the loop
foreach ($row as $k => $v){
   $sql .= "($row[$k], $row[$k]),";
}

// Remove final comma
rtrim($sql, ",");

$final_sql = "INSERT INTO table_name VALUES " . $sql;
mysql_query($sql, $db);
?>

 

Regards

Rich

Link to comment
Share on other sites

If you don't need the UID of newly created records, definitely a multi-valued insert -- just remember that there _is_ a max_packet_length, but it's usually a mb or two, so it's usually not an issue.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.