上次我问如何将循环保存到数据库现在想要显示表中的值然后更新它但它只保存最后一行。
$id = ($_REQUEST['StudentNumber']);
$result2= mysql_query("select NameofSiblings, Age, HEA, CivilStatus, Occupation FROM $tblname WHERE StudentNumber='$id'");
$child = $_REQUEST['NumberofChildren'];
for($n=1;$n<=$child;$n++)
{
while($row=mysql_fetch_array($result2))
{
echo "<table>
<tr>
<td class='siblings'><input type='text' name='sibname[]' style='width: 150px;' value=".$row['NameofSiblings']."></td>
<td class='siblings'><input type='text' name='sibage[]' style='width: 35px;' value=".$row['Age']."></td>
<td class='siblings'><input type='text' name='sibhea[]' style='width: 260px;' value=".$row['HEA']."></td>
<td class='siblings'><input type='text' name='sibcs[]' style='width: 100px;' value=".$row['CivilStatus']."></td>
<td class='siblings'><input type='text' name='siboccu[]' style='width: 100px;' value=".$row['Occupation']."></td>
</tr>
</table>";
}
}
?>
<input type="hidden" name="n" value="<?php echo $child; ?>">
我做得对吗?这是我的更新查询:
$n=intval($_POST['n']);
for($i=0;$i<$n;$i++)
{
$sibname =$_POST['sibname'][$i];
$sibage =$_POST['sibage'][$i];
$sibhea =$_POST['sibhea'][$i];
$sibcs =$_POST['sibcs'][$i];
$siboccu =$_POST['siboccu'][$i];
$query = "UPDATE $tblname SET NameofSiblings = '$sibname', Age = '$sibage', HEA = '$sibhea', CivilStatus = '$sibcs', Occupation = '$siboccu' WHERE StudentNumber='$sn' ";
}
我希望有人能理解它。
答案 0 :(得分:0)
当你遍历POST
值时,你创建了一个SQL查询字符串,但是你没有在循环内(或者在它之外)执行它(即调用mysql_query
)。您需要在循环的下一次迭代发生之前执行查询,否则您将丢失该值。
for ($i=0; $i<$n; $i++) {
$sibname =$_POST['sibname'][$i];
$sibage =$_POST['sibage'][$i];
$sibhea =$_POST['sibhea'][$i];
$sibcs =$_POST['sibcs'][$i];
$siboccu =$_POST['siboccu'][$i];
$query = "UPDATE $tblname SET NameofSiblings = '$sibname', Age = '$sibage', HEA = '$sibhea', CivilStatus = '$sibcs', Occupation = '$siboccu' WHERE StudentNumber='$sn' ";
mysql_query($query); // execute query here for each iteration of the loop
}
希望有意义,您应该停止使用mysql_*
函数,因为它们现在已被弃用,并且非常容易受到SQL注入攻击。
看看这些链接,这应该有很多帮助。