mysql - Inserting multiple rows linked by fk - php -
i'm trying insert data form table teams, team names , fk each age group. i'm getting age group id simple select function , looping id's on form. when run insert function, i'm getting 4 rows first form data. if there 3,4 or 5 different age groups, insert names , age_group fk alle groups
the form , age group loop:
<form action="" method="post"> <?php $ages = get_age_groups_in_cups($db); foreach($ages $age){ ?> <input type="text" name="age_group[]" value="<?php echo $age['age_id'];?>"> <input type="text" name="team_name[]"> <input type="text" name="team_name[]"> <input type="text" name="team_name[]"> <input type="text" name="team_name[]"> <?php } ?> <button name="insert_rows">save</button> </form>
i'm running insert function when insert button has been submitted, i'm getting result "first" age_group
the function:
function insert_teams($db){ $age_group = $_post['age_group']; $team_name = $_post['team_name']; foreach ($age_group $key => $error){ $sql = "insert teams (team_name, age_group_fk) values (:team_name, :age_group_fk)"; $stmt = $db->prepare($sql); $stmt->execute(array( 'team_name' => $team_name, 'age_group_fk' => $age_group[$key] )); } }
you should add level on input array.
you use <input type="text" name="team_name[]">
each age group.
but age groups in same array.
use instead like
<?php <form action="#" method="post"> <?php $ages = get_age_groups_in_cups($db); foreach($ages $age){ ?> <input type="text" name="team_name[<?= $age['age_id'] ?>][]"> <input type="text" name="team_name[<?= $age['age_id'] ?>][]"> <input type="text" name="team_name[<?= $age['age_id'] ?>][]"> <input type="text" name="team_name[<?= $age['age_id'] ?>][]"> <?php } ?> <button name="insert_rows">save</button> </form>
Comments
Post a Comment