【发布时间】:2013-11-30 11:08:32
【问题描述】:
我是一名 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';
【问题讨论】:
-
此代码不会尝试将任何数据写入任何数据库。究竟是什么问题?
-
谢谢,省略了我使用的 PHP 代码,已编辑。
-
@timus2001 谢谢,删除了那个位。
标签: php html mysql arrays forms