MySQL / PHP:将表单数组插入数据库?

时间:2013-11-17 07:50:11

标签: php html mysql arrays forms

我是一名PHP新手,使用foreach语句将表单中的数组插入数据库时​​出现问题。 我正在尝试创建一个接受每个主题的分数,成绩和评论的表单。但是,只有最后一个主题插入到数据库中。主题列表是从以前注册的科目加载的(我没有问题)。我的问题是让所有主题都保存回数据库。 这是我使用的形式:

<legend>ENTER RESULTS:</legend>
<input type="hidden" name="results[]" value= "<?php foreach ($subjects as $subject):?>
<ul>
<li> <input type="text" name="subject_name" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
          </label>
     <label for="subject_score">SCORE:</label>
    <input type="text" name="subject_score" size="5" value = "<?php
        htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
    <input type="text" name="subject_grade" size="5" value = "<?php
        htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
    <input type="text" name="subject_comment" size="30" value = "<?php
        htmlout($subject_comment);?>"/> </div></li>

    <?php endforeach; ?>
    <input type="hidden" name="student_id" value="<?php
        htmlout($student_id); ?>
  </fieldset>

这是我使用的PHP代码:

if (isset($_GET['result']))
{
try
{
  $sql = 'INSERT INTO results SET
      student_id = :student_id,
      subject_name = :subject_name,
      subject_grade = :subject_score,
      subject_grade = :subject_grade,
      subject_comment = :subject_comment';
  $s = $pdo->prepare($sql);

  foreach ($_POST['results'] as $result)
  {
  $s->bindValue(':student_id',$_POST['student_id']);
  $s->bindValue(':subject_name', $_POST['subject_name']);
  $s->bindValue(':subject_score', $_POST['subject_score']);
  $s->bindValue(':subject_grade', $_POST['subject_grade']);
  $s->bindValue(':subject_comment', $_POST['subject_comment']);
  $s->execute();
  }
  }
catch (PDOException $e)
{
  $error = 'Could not Register the Student for the Subjects, Please try again'.$e->GetMessage();
  include 'error.html.php';
  exit();
}
echo 'Success';

1 个答案:

答案 0 :(得分:0)

您可以在数组中使用表单元素,例如 subject_score []

你的表格应该像

foreach
<input type="text" name="subject_name[]" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
          </label>
     <label for="subject_score">SCORE:</label>
    <input type="text" name="subject_score[]" size="5" value = "<?php
        htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
    <input type="text" name="subject_grade[]" size="5" value = "<?php
        htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
    <input type="text" name="subject_comment[]" size="30" value = "<?php
        htmlout($subject_comment);?>"/> </div></li>
endforeach

然后你可以像下面那样收集这些价值

foreach($_POST['subject_name'] as $key=>$val){
  //val will hold subject name
}