gpt4 book ai didi

php - MySQL/PHP : Insert form array into database?

转载 作者:行者123 更新时间:2023-11-30 01:02:07 24 4
gpt4 key购买 nike

我是一名 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';

最佳答案

您可以在数组中使用表单元素,例如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
}

关于php - MySQL/PHP : Insert form array into database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com