2016-11-10 59 views
0

我試圖從表單中插入數據到表格團隊,所有團隊名稱和fk到每個年齡段。 我從一個簡單的SELECT函數中獲取年齡組ID,然後在表單上循環使用ID。 當我運行插入功能時,我只從數據的第一個表單中獲得4行。 所以,如果有3,4或5個不同的年齡組,我想插入名稱和AGE_GROUP FK的全部組插入由fk鏈接的多行 - php

的形式和年齡組循環:

<form action="" method="post"> 
    <?php 
     $ages = get_age_groups_in_cups($db); 
     foreach($ages as $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> 

我跑當插入按鈕已經提交了插入功能,但我只得到了結果從「第一」 AGE_GROUP

功能:

function insert_teams($db){ 
    $age_group = $_POST['age_group']; 
    $team_name = $_POST['team_name']; 

    foreach ($age_group as $key => $error){ 
     $sql = "INSERT INTO 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] 
      )); 
     } 

    } 
+0

你怎麼想,什麼是這兩個數組的大小? –

+0

@YourCommonSense如果只有一個年齡組,年齡數組爲0並且包含年齡編號,並且team_name長度爲0123。如果有更多的團隊,team_name是8,12,16等,年齡只要有年齡組 –

+0

我不明白你的答案。你能直截了當地說,這兩個陣列的大小是多少? –

回答

0

你SH應該在你的輸入數組上添加一個級別。

您使用<input type="text" name="team_name[]">爲每個年齡組。

但基本上所有年齡組都會在同一陣列中。

使用,而不是像

<?php 
    <form action="#" method="post"> 
     <?php 
    $ages = get_age_groups_in_cups($db); 
      foreach($ages as $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>