gpt4 book ai didi

php - 将表单值插入数据库

转载 作者:行者123 更新时间:2023-11-29 11:44:18 25 4
gpt4 key购买 nike

如何在数据库中插入此表单的值?

<tr>
<td>1. Do you feel well and healthy?</label></td>
<input type="hidden" name="question" value="1. Do you feel well and healthy?">
<td><input type="radio" name="answer" value="Yes" checked></td>
<td><input type="radio" name="answer" value="No"></td>
<td><input type="text" name="remarks"></td>
</tr>
<tr>
<td><ul><li>Have any flu or cold?</li></ul></td>
<input type="hidden" name="question" value="Have any flu or cold?">
<td><input type="radio" name="answer" value="Yes" checked> </td>
<td><input type="radio" name="answer" value="No"></td>
<td><input type="text" name="remarks"></td>
</tr>

因为当我将此数据插入数据库时​​,它只插入第二个表行“有烟道”中的最后一个值....

$medical = new MedicalHistory;
$medical->username = $value;
$medical->question = $data['question'];
$medical->answer = $data['answer'];
$medical->remarks = $data['remarks1'];
$medical->save();

我使用 Laravel 作为框架

最佳答案

仅插入第二个表单的原因是您在字段中重复使用相同的名称。

一种解决方案是为所有字段提供唯一的名称(单选按钮对除外)。

更好的解决方案是进行数组输入,我快速搜索了您并提出了这个:How to get form input array into PHP array

您应该将代码修改为数组变量,因此如果您想保存多个问题,请在两个问题字段中使用名称“question[]”而不是“question”。

前端表示例:

<tr>
<td>1. Do you feel well and healthy?</label></td>
<input type="hidden" name="question[]" value="1. Do you feel well and healthy?">
<td><input type="radio" name="answer[0]" value="Yes" checked></td>
<td><input type="radio" name="answer[0]" value="No"></td>
<td><input type="text" name="remarks[]"></td>
</tr>
<tr>
<td><ul><li>Have any flu or cold?</li></ul></td>
<input type="hidden" name="question[]" value="Have any flu or cold?">
<td><input type="radio" name="answer[1]" value="Yes" checked> </td>
<td><input type="radio" name="answer[1]" value="No"></td>
<td><input type="text" name="remarks[]"></td>
</tr>

要在 PHP 逻辑中处理新的数据格式,您应该执行以下操作:

$question = $_POST['question'];
$answer = $_POST['answer'];
$remark = $_POST['remarks'];

foreach( $question as $key => $q ) {
print "The question is ".$q.", answer is ".$answer[$key].
", and remarks are ".$remark[$key].". Thank you\n";
}

既然你想保存数据,你应该这样做:

$value = 'idk_where_you_assign_names';
$question = $_POST['question'];
$answer = $_POST['answer'];
$remark = $_POST['remarks'];

foreach( $question as $key => $q ) {
$medical = new MedicalHistory;
$medical->username = $value;
$medical->question = $q;
$medical->answer = $answer[$key];
$medical->remarks = $remark[$key];
$medical->save();
}

经过我的编辑,它现在应该可以工作了。

关于php - 将表单值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223675/

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