padams Posted September 6, 2007 Share Posted September 6, 2007 I've written a foreach routine that should insert new records into a table, but for some reason it only works some of the time. Sometimes it creates only a few records and ignores others, and ocasionally the data inserted doesn't even match what was entered in the form! The tricky part (at least for me!) is that the form page has drop-down menus for each try/touchdown scored, but the number of these menus varies depending on a value entered on a previous page. Because the number of drop-downs varies, I (with substantial help from some of you) had to write the foreach routine that checked how many values were posted and created a new query for each one. Since the Submit button is also posted, I then added a query that deletes any extra tries/touchdowns (since the button doesn't have a tryPlayer value attached). foreach ($_POST as $p){ if ($p != "Submit"){ $createtry_sql = sprintf("INSERT into tries (tryOpponent, tryTeam, trySeason, tryPlayer) VALUES ('%s', '%s', '%s', '%d')", $_SESSION['creatematch']['opposition'], $_SESSION['creatematch']['ottersteam'], $_SESSION['creatematch']['season'], $_POST['try'.$p] ); $createtry_query = mysql_query($createtry_sql) or die(mysql_error()); } } $removetry = "DELETE from tries where tryPlayer = ''"; $removetry_query = mysql_query($removetry) or die(mysql_error()); I also noticed that even though all players have ID numbers, when I don't include the $removetry query, some of the try records have a tryPlayer of 0. I think the code I wrote to generate the drop-downs is correct - but not 100% sure. $count = 1; do { ?> Try <?php echo $count; ?>: <select name="try<?php echo $count; ?>"> <?php do { ?> <option value="<?php echo $rstrylists['playerID']; ?>"><?php echo $rstrylists['playerFirstName']; ?> <?php echo $rstrylists['playerLastName']; ?></option> <?php } while ($rstrylists = mysql_fetch_assoc($trylists_query)) ?></select><br> <?php $count++; mysql_data_seek($trylists_query, 0); } while ($count <= $trycount) Quote Link to comment Share on other sites More sharing options...
ToonMariner Posted September 6, 2007 Share Posted September 6, 2007 You should not perform multiple inserts inside a for loop - use the loop to construct a single query string that will add all the records you need.... this has already been addressed in one of your other threads. Quote Link to comment Share on other sites More sharing options...
padams Posted September 6, 2007 Author Share Posted September 6, 2007 Sorry, hadn't checked that post as I thought it had been solved. Still new to forums and correct etiquette! I reopened that thread as I couldn't get your suggestion to work. End of thread!! 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.