[英]inserting a dynamically generated $_POST values from a form into mysql from php
我正在尝试从我的表单插回数据库值。
<?php do { ?>
<tr>
<td><?php echo $row_questions['question']; ?><br /><table><tr><td style=
"padding:15px; text-align:center">
<label>
<center><input type="radio" name="answers_<?php echo $row_questions['id']; ?>_<?php echo $row_questions['sub_category']; ?>" value="1" id="answers_1" /></center><br />
Low</label>
</td><td style="padding:15px; text-align:center">
<label>
<center><input type="radio" name="answers_<?php echo $row_questions['id']; ?>_<?php echo $row_questions['sub_category']; ?>" value="2" id="answers_2" /></center><br />
Fairly Low</label>
</td><td style="padding:15px; text-align:center">
<label>
<center><input type="radio" name="answers_<?php echo $row_questions['id']; ?>_<?php echo $row_questions['sub_category']; ?>" value="3" id="answers_3" /></center><br />
Average</label>
</td><td style="padding:15px; text-align:center">
<label>
<center><input type="radio" name="answers_<?php echo $row_questions['id']; ?>_<?php echo $row_questions['sub_category']; ?>" value="4" id="answers_4" /></center><br />
Fairly High </label>
</td><td style="padding:15px; text-align:center">
<label>
<center><input type="radio" name="answers_<?php echo $row_questions['id']; ?>_<?php echo $row_questions['sub_category']; ?>" value="5" id="answers_5" /></center><br />
High</label>
</td></tr></table><br />
</tr>
<?php } while ($row_questions = mysql_fetch_assoc($questions)); ?>
表单从我的数据库中的表(称为问题)中获取问题。 它们分为三类,任何时候都只提取一类问题。
我需要将每个答案分别插入另一个表(称为user_answers)。
我很难找到如何解决这个问题,而且我已经开始努力了!
表单设法通过$ _POST传递一个值,当我print_r($_POST);
我明白了
数组([answers_90_5] => 3 [answers_91_5] => 3)
90和91是问题ID,5是两个实例中的子类别。
从这里我很难过。
如何识别每个帖子的这些部分以及答案,并将它们作为一行插入表格中?
我很好地正常进行MySQL插入和标准表单传递值等但我完全不知道如何做到这一点!
提前谢谢了!
使用多维数组可以简化迭代工作:
<input
type="radio"
name="answers[<?php echo $row_questions['id']; ?>][<?php echo $row_questions['sub_category']; ?>]"
value="1"
id="answers_<?php echo $row_questions['id'] . '_' . $row_questions['sub_category']; ?>" />
调试这个应该给你$_POST
填充一个喜欢的数组:
Array ( [answers] => Array(
90 => Array ( 5 => 3 ),
91 => Array ( 5 => 3 ),
))
确定,将您的查询分开,将post one和sub cat one分别用于查询1,查询2对cat 2和sub cat 2执行相同的操作。
很简单。
我认为另一个提示多暗阵列的答案很有意义。 以为我仍然会提供一个如何解析字符串的示例。 它可能很简单:
foreach ($post as $k => $v) {
$parts = explode('_', $k);
$questionId = $parts[1];
$questionCategoryId = $parts[2];
$sql = "INSERT INTO answers (questionId, subCategoryId, answerValue ) VALUES ($questionId, $questionCategoryId, $v)";
....
}
...希望能够更好地逃避POST数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.