私はここにjsfiddleを持っています:http: //jsfiddle.net/ybZvv/58/
フィドルの手順に従ってください:
1:フィドルを開いたら、[質問を追加]ボタンを2回クリックすると、2行追加されます。
2:1行目で回答ボタン「A」、「C」を選択し、2行目で回答ボタン「A」、「B」、「E」を選択します。選択した各回答ボタンのテキスト入力値が下に表示されます。
今、私がやりたいのは、質問番号と回答値をデータベースに投稿することです。
投稿すると、データベースは次のようになります。
質問表:
QuestionId (Question Number)
1
2
回答表:
AnswerId (auto) QuestionId Answer
1 1 A
2 1 C
3 2 A
4 2 B
5 2 E
私の質問は、以下のmysqliコードに回答と正しい質問番号を投稿して、それらの回答と質問番号を「質問」テーブルと「回答」テーブルに挿入する方法です。
以下にmysqli/phpコードを設定しましたが、回答と関連する質問番号を正しく挿入できるように再調整する必要があります。
$i = 0;
$c = count($_POST['numQuestion']); //count number of rows
for($i = 0; $i < $c; $i++ ){
$questionsql = "INSERT INTO Question (QuestionId)
VALUES (?)";
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("i", $_POST['numQuestion'][$i]);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastID = $mysqli->insert_id;
$answersql = "INSERT INTO Answer (QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$insertanswer->bind_param("is", $lastID, $_POST['value'][$i]);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
}
$insertanswer->close();
}
上記のシナリオでvar_dump($ _ POST)を実行しましたが、これが出力されます。
array(2) {
["numQuestion"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "2"
}
["submitDetails"]=> string(14) "Submit Details"
["value"]=> array(4) {
["answerARow"]=> string(1) "A"
["answerCRow"]=> string(1) "C"
["answerBRow"]=> string(1) "B"
["answerERow"]=> string(1) "E"
}
}
同一の2つのエラーが発生します。
警告:mysqli_stmt :: execute():( 23000/1048):257行目の/.../で列'Answer'をnullにすることはできません警告:mysqli_stmt :: execute():(23000/1048):列' Answer ' 257行目の/.../でnullにすることはできません
アップデート:
多次元配列を含めるようにフィドルを更新しました。申し訳ありませんが、入力するのを忘れましたが、このためのコード行は次のとおりです。
var $newBtn = $(("<input class='answerBtnsRow answers' type='button' style='display:%s;' onclick='btnclick(this, " + gQuestionIndex + ");' />").replace('%s',$this.is(':visible')?'inline-block':'none')).attr('name', "value[" + gQuestionIndex + "][]").attr('value', $this.val()).attr('class', $this.attr('class')).attr('id', $this.attr('id')+'Row');
私の提案は、value [n] []の形式で多次元配列を使用することです。ここで、nは質問番号です。この新しい設定では、最終的に次の入力フィールドが表示されます。
<input type="hidden" value="A" name="value[1][]">
<input type="hidden" value="B" name="value[1][]">
<input type="hidden" value="A" name="value[2][]">
<input type="hidden" value="C" name="value[2][]">
<input type="hidden" value="E" name="value[2][]">
選択した値はvalue属性にエンコードされていることに注意してください。name属性には、値が属する質問のみが含まれます。