我是php的初学者,我正在尝试将此循环保存到数据库,但它只保存数据库的最后一行..我希望有人能提前回答这个问题。
<?php
$child = $_REQUEST['NumberofChildren'];//requested from the lastpage
echo "<form method='post' action='familysave.php'>";
for($n=1; $n<=$child; $n++)
{
echo "<table>
<tr>
<td><input type='text' name='sibname' placeholder='Fullname' style='width: 150px;' required></td>
<td><input type='text' name='sibage' placeholder='Age' style='width: 35px;' required></td>
<td><input type='text' name='sibhea' placeholder='Highest Educational Attainment' style='width: 260px;'></td>
<td><input type='text' name='sibcs' placeholder='Civil Status' style='width: 100px;' required></td>
<td><input type='text' name='siboccu' placeholder='Occupation' style='width: 100px;' required></td>
</tr>
</table>";
}
?>
<input type="submit" value="Save">
<?php echo "</form>";
?>
这是familysave.php的代码
<?php
$conn = mysql_connect($host, $username, $password);
if(! $conn)
{
die('Could not connect: ' . mysql_error());
}
$sibname =$_POST['sibname']
$sibage =$_POST['sibage']
$sibhea =$_POST['sibhea']
$sibcs =$_POST['sibcs']
$siboccu =$_POST['siboccu']
$sql = "INSERT INTO $tblname (NameofSiblings, Age, HEA, CivilStatus, Occupation) VALUES ('$sibname', '$sibage', '$sibhea', '$sibcs', '$siboccu')";
mysql_select_db($dbname);
$retval = mysql_query($sql, $conn);
if(! $retval)
{
die('Could not Enter Data:' . mysql_error());
}
mysql_close($conn);
?>
答案 0 :(得分:0)
即使在循环中重复字段集,所有FORM字段也具有相同的名称。将这些名称更新为name='sibname[]'
,然后在PHP中运行所有这些名称以获取值。
<强>像强>
<强>步骤1:强>
for($n=1; $n<=$child; $n++)
{
echo "<table>
<tr>
<td><input type='text' name='sibname[]' placeholder='Fullname' style='width: 150px;' required></td>
<td><input type='text' name='sibage[]' placeholder='Age' style='width: 35px;' required></td>
<td><input type='text' name='sibhea[]' placeholder='Highest Educational Attainment' style='width: 260px;'></td>
<td><input type='text' name='sibcs[]' placeholder='Civil Status' style='width: 100px;' required></td>
<td><input type='text' name='siboccu[]' placeholder='Occupation' style='width: 100px;' required></td>
</tr>
</table>";
}
<强>步骤2:强>
在表单中添加隐藏字段以指示添加的子项数
<input type="hidden" name="n" value="<?php echo $child; ?>">
第3步:
现在运行一个循环来获取值
$n=intval($_POST["n"]);
for($i=0;$i<$n;$i++)
{
$sibname =$_POST['sibname'][$i]; // better to use isset() as well
$sibage =$_POST['sibage'][$i];
$sibhea =$_POST['sibhea'][$i];
$sibcs =$_POST['sibcs'][$i];
$siboccu =$_POST['siboccu'][$i];
// Now save these values but do not use the deprecated MySQL API, see the link below.
}