普通网友 2016-12-31 11:37
浏览 63
已采纳

如何在while循环中从动态生成的文本框中发布多个条目

please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.

<?php
session_start();
include 'header_staff.php';

$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';

?>
  • 写回答

3条回答 默认 最新

  • dqtok88424 2016-12-31 11:53
    关注

    The solution to your problem is to use your input arrays by simply adding [] to the input names:

    while($subj=mysql_fetch_array($sql)){
      echo $subj['name'];
      echo '<input type="text" name="ca1[]" />';
      echo '<input type="text" name="ca2[]" />';
      echo '<input type="text" name="exam[]" /><br><br>';
    }
    

    Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):

    while($subj=mysql_fetch_array($sql)){
      echo $subj['name'];
      echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
      echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
      echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
    }
    

    This way you can easily identify values from the resulting array after the post.

    PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题