Rachel Posted February 22, 2011 Share Posted February 22, 2011 I am trying to insert records from an foreach array, it only inserts the first record and I cannot work out how to get it to loop through all of the records. Thank you foreach($_SESSION['post_data_array'] AS $seat) { $rowId = substr($seat, 0, 1); $columnId = substr($seat, 1); echo $rowId . $columnId . ", "; } $sql125 = "INSERT INTO booked_seats(booking_id, row_id, column_id) values ('$book_id', '$rowId', '$columnId')"; $result125 = mysql_query($sql125); if ($result125) { echo "worked"; } else { echo "didnt work"; } Quote Link to comment https://forums.phpfreaks.com/topic/228520-insert-into-table-from-array/ Share on other sites More sharing options...
PaulRyan Posted February 22, 2011 Share Posted February 22, 2011 Place the SQL statement inside of the Foreach loop. Regards, PaulRyan. Quote Link to comment https://forums.phpfreaks.com/topic/228520-insert-into-table-from-array/#findComment-1178304 Share on other sites More sharing options...
Pikachu2000 Posted February 22, 2011 Share Posted February 22, 2011 Running a query in a loop is resource intensive and should be avoided whenever possible. Build the query string in a loop, then execute one query. Quote Link to comment https://forums.phpfreaks.com/topic/228520-insert-into-table-from-array/#findComment-1178319 Share on other sites More sharing options...
jcbones Posted February 23, 2011 Share Posted February 23, 2011 Try something like: (Pik's suggestion) foreach($_SESSION['post_data_array'] AS $seat) { $rowId = substr($seat, 0, 1); $columnId = substr($seat, 1); echo $rowId . $columnId . ", "; $sql[] = "('$book_id', '$rowId', '$columnId')"; } $sql125 = "INSERT INTO booked_seats(booking_id, row_id, column_id) values " . implode(',',$sql); Quote Link to comment https://forums.phpfreaks.com/topic/228520-insert-into-table-from-array/#findComment-1178422 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.