【发布时间】:2015-05-11 07:04:30
【问题描述】:
我在页面上有一个由 for 循环创建的表单。
$scripte = ($_POST["scriptake"]);
$scriptot = ($_POST["scriptot"]);
include 'config.php';
echo '<h2>'.$scripte.' Equipment</h2>';
echo '<h2>Total Hours '.$scriptot.'</h2>';
echo '<table class="table table-responsive">
<tr>
<form action="equiptest.php" method="post">
<th>Script Hour</th>
<th>Equipment Required</th>
<th>Stage</th>
</tr>';
$x = 1;
$p = 1;
$r = 1;
while($x <= $scriptot ) {
echo "<tr>
<td>".$x++."</td>
<td>
<input name='equip[".$r++."]'>
</td>
<td>
<input name='stage[".$p++."]'>
<input name='ohyeah' type='hidden' value= '".$scriptot."'>
</td>
</tr>";
}
echo '<tr>
<td colspan="2">
<input type="submit" class="btn btn-primary">
</td>
</tr>
</form>
</table>';
如您所见,带有输入的表单是使用 for 循环创建的。表单中的值收集在数组equip[] 和stage[] 中。如果有意义的话,可以为索引设置一个计数器。然后将表单提交到以下脚本。
include 'config.php';
$scriptot = ($_POST["ohyeah"]);
$y = 1;
$r= 1;
foreach($_POST['equip'] as $key => $value) {
foreach($_POST['stage'] as $key => $stage) {
$query = $con->stmt_init();
$statement = $con->prepare("INSERT INTO dgam_equip
(equiplist,stage) VALUES (?,?)");
$statement->bind_param('ss',$value,$stage);
$statement->execute();
}
}
echo 'success';
//bind result variables to be printed
$statement->close();
echo '<br><br><br><br><br>';
我正在尝试将数组插入数据库。
ID |装备列表 |舞台
ID 装备[] 舞台[]
我正在尝试嵌套一个 foreach 循环或将数组添加到正确的行中。我可以进入该行,但数据执行了很多次。我猜那是因为 foreach 循环正在执行第二个 foreach 循环 将此类数据放入数据库的正确方法是什么。我正在尝试先设置一个数组,但我很挣扎。
【问题讨论】:
-
编辑并删除不必要的html,唯一相关的是实际循环,您还应该改进代码的缩进,使其更易于阅读。
-
很抱歉,但在过去,我因未提交代码而获得 6 票反对。我现在起飞
-
只需使用一个循环并使用索引来访问两个数组。您可以使用
sizeof获取数组的大小,并且您可能希望在循环之前比较数组的大小 -
数组的大小每次都相同
-
您的标签错误:
<table ...><tr><form ..>...</tr>。它们没有正确匹配,<form>不是 valid content 的<tr>
标签: php html mysql arrays foreach