HuggieBear Posted March 1, 2009 Share Posted March 1, 2009 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 Quote Link to comment Share on other sites More sharing options...
fenway Posted March 1, 2009 Share Posted March 1, 2009 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. Quote Link to comment Share on other sites More sharing options...
HuggieBear Posted March 2, 2009 Author Share Posted March 2, 2009 I'm not interested in the UID so I'll changed it to a single insert and I'll see what happens. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.