php - INSERT in main foreach() or in separate foreach()? -


i have cache table rebuilt occasionally:

$sql = 'insert sometable (...fields...) values (...values...)'; $stmt = $pdo->prepare($sql, array(pdo::attr_cursor => pdo::cursor_fwdonly)); $items_to_insert[] = array();  foreach ($item $i) {     $details = array();      // lots of things here, such as:     $details[':username'] = $['username'];      $items_to_insert[] = $details }  foreach ($items_to_insert $i) {     $stmt->execute($i); } 

what should take consideration decide if better off run $stmt->execute() in first foreach , eliminate second foreach , $items_to_insert array? there way have execute() run concurrently next foreach loop? application run on variety of hardware i not interested in specific case of benchmarking on workstation, rather i interested in learning intricacies of situation make better use of pdo best practices.

the best practice use none of foreach loops. using sql queries in loop bad idea, , kind of query (insert, select, update or delete) doesn't matter).

what should make one query using loop , execute once. unfortunately, pdo doesn't provide automatic way this, have write manually.

look @ accepted answer of question, need: pdo prepared inserts multiple rows single query


Comments