【发布时间】:2026-01-16 09:40:01
【问题描述】:
我正在尝试将表单中的数据插入到表格团队中,其中包含所有团队名称和每个年龄组的 fk。 我从一个简单的 SELECT 函数中获取年龄组 ID,然后在表单上循环该 ID。 当我运行插入函数时,我只从第一个表单中获取 4 行数据。 所以如果有 3,4 或 5 个不同的年龄组,我想为所有组插入名称和 age_group fk
形式和年龄组循环:
<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]
));
}
}
【问题讨论】:
-
你怎么看,这两个数组的大小是多少?
-
@YourCommonSense 如果只有一个年龄组,则年龄数组为 0 并包含年龄编号,并且 team_name 的长度为 0123。如果有更多组,则 team_name 为 8、12、16 等,只要有年龄组,年龄就可以了
-
我不明白你的回答。你能直截了当地说,这两个数组的大小是多少?
-
这里是发布数据的 print_r。来自团队 1 - 团队 4 应该在 age_group 1 中,其余在 age_group 4 数组中([age_group] => 数组([0] => 1 [1] => 4)[team_name] => 数组([0] => 团队 1 [1] => 团队 2 [2] => 团队 3 [3] => 团队 4 [4] => 团队 5 [5] => 团队 6 [6] => 团队 7 [7] = > 团队 8 ) [newStepTwo] => )