如何在数据库中插入此表单的值?
<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>
因为当我要将这些数据插入数据库时,它只会插入第二个表行“ have flue”中的最后一个值。
$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/