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 Link to comment https://forums.phpfreaks.com/topic/147418-solved-which-insert-method-is-better/ 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. Link to comment https://forums.phpfreaks.com/topic/147418-solved-which-insert-method-is-better/#findComment-773792 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. Link to comment https://forums.phpfreaks.com/topic/147418-solved-which-insert-method-is-better/#findComment-774613 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.