簡體   English   中英

如何正確發布值並將其插入數據庫?

[英]How to post and insert values into the database correctly?

我想使用這種格式的多維數組:值[n]的[],其中n是問題編號。 使用此新設置,您應該最終獲得以下復選框字段:

<input type="checkbox" value="A" name="value[1][]">
<input type="checkbox" value="B" name="value[1][]">
<input type="checkbox" value="A" name="value[2][]">
<input type="checkbox" value="C" name="value[2][]">
<input type="checkbox" value="E" name="value[2][]">

請注意,所選值被編碼在value屬性中。 name屬性僅包含值所屬的問題。

因此,以上輸入說明了這一點:

question 1: answer: A
question 1: answer: B
question 2: answer: A
question 2: answer: C
question 2: answer: E

我想將這些詳細信息插入下面的“問題”和“答案”數據庫表中:

問題表:

SessionId    QuestionId

MUL             1
MUL             2

答案表:

 AnswerId (auto)  SessionId  QuestionId   Answer
 1                MUL        1            A
 2                MUL        1            B
 3                MUL        2            A
 4                MUL        2            C
 5                MUL        2            E

現在,我嘗試編寫下面的mysqli / php代碼以將這些值插入數據庫,但是我收到錯誤,並且在實現自己想要達到的目標方面失敗。 我需要能夠在相關表中正確插入正確值的幫助。

以下是php / mysqli代碼:

var_dump($_POST);  

$i = 0;
$c = count($_POST['numQuestion']);

for($i = 0;  $i < $c; $i++ ){

/*
    switch ($_POST['gridValues'][$i]){

    case "3": 
    $selected_option = "A-C";
    break;

    case "4": 
    $selected_option = "A-D";
    break;

    case "5": 
    $selected_option = "A-E";
    break;

    default:
    $selected_option = "";
    break;

    }   

    */ needed later on when I insert grid values   



$results = $_POST['value'];
foreach($results as $id => $value) {
$answer = $value;

 $questionsql = "INSERT INTO Question (SessionId, QuestionId) 
    VALUES (?, ?)";

    $sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');


    if (!$insert = $mysqli->prepare($questionsql)) {
      // Handle errors with prepare operation here
    }

$insert->bind_param("si", $sessid, $id);

        $insert->execute();

        if ($insert->errno) {
          // Handle query error here
        }

        $insert->close();

        $insert->insert_id;

        foreach($value as $answer) {

         $answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer) 
    VALUES (?, ?, ?)";

      if (!$insertanswer = $mysqli->prepare($answersql)) {
      // Handle errors with prepare operation here
    }  

    $insertanswer->bind_param("sis" $sessid, $lastID, $answer);

        $insertanswer->execute();

        if ($insertanswer->errno) {
          // Handle query error here
        }

        $insertanswer->close();


}

}

}

var_dump($_POST)在下面輸出:

    array(3) { 
["numQuestion"]=> array(2) { 
[0]=> string(1) "1" 
[1]=> string(1) "2" 
}  
["submitDetails"]=> string(14) "Submit Details" ["value"]=> array(4) { 
["answerARow"]=> string(2) "on" 
["answerCRow"]=> string(2) "on" 
["answerBRow"]=> string(2) "on" ["answerERow"]=> string(2) "on"
 } 
}

以下是我收到的錯誤以及每個錯誤鏈接到的代碼行:

警告:第252行的/.../中為foreach()提供了無效的參數

foreach($value as $answer) {

警告:mysqli_stmt :: execute():(23000/1062):/ 242 /行中的/.../中的鍵“ PRIMARY”的條目“ MUL-0”重復

上面的錯誤表明沒有插入任何問題號,因為它一直顯示為“ 0”

因此,您似乎想要做的主要事情是解決皮膚無用復選框的問題。 我以前做過。 我這樣做的方法是使用跨度綁定到隱藏的復選框。

我使用了span,因為我不確定提交表單時表單字段中的按鈕是否會發布值。 我知道跨度不會。 這樣可以確保僅提交您的復選框值,而不提交“ cover-up”值。

在您的jsFiddle中,在updateAnswer()函數中,您具有以下代碼:

if (!bDisableAppend) {
    // append those values to the form
    var input = '<input type="checkbox" id="' + hid + '" name="value[' + id + ']" checked /><label for="' + hid + '">' + value + '</label>';
    _oCurrAnswerContainer.append(input);
}

在該代碼中,您將復選框的name屬性設置為諸如value[answerARow] 那就是你的問題所在。

TBH,這對我來說很難遵循您的代碼,因此我想出的解決方案可能需要進行一些調整,以添加我在您的示例中錯過的任何隱藏技巧。 但是這是我想出的:

jsFiddle

JS / jQuery:

var options = ["A", "B", "C", "D", "E", "F", "G", "H"];


// this will bind the event handler to the document element, so that even when a new element is created,
// the event will be automatically bound to it.
$(document).on("click", "span.checkbox", function() {
    $("#chk"+ $(this).attr("id")).click();
    $(this).toggleClass("unselected selected");
});


$("#btnAddQuestion").click(function() {
    var questionNum = $("#tblQuestions tbody tr").length+1;

    var cell = $(document.createElement("td")).addClass("optAns").html("Answer:<br />");

    // loop through the options and add them to the cell
    for (var i in options)    
    {
        $(cell).append(
            // the front-end overlay for the checkbox
            $(document.createElement("span"))
                .addClass("checkbox unselected")
                .attr("id", "Value"+ questionNum + options[i])
                .html(options[i])
        ).append(
            // the hidden checkbox that will post the actual value
            $(document.createElement("input"))
                .attr("type", "checkbox")
                .addClass("hidden")
                .attr("id", "chkValue"+ questionNum + options[i])
                .attr("name", "value["+ questionNum +"][]")
                .attr("value", options[i])
        );
    }

    // create a new table row, append the "option and answer" cell
    // and question number cell, and append it to the table body
    $(document.createElement("tr"))
        .append(cell)
        .append($(document.createElement("td")).addClass("questionNum").html(questionNum))
        .appendTo("#tblQuestions tbody");
});

HTML:

<div id="detailsBlock">
    <button id="btnAddQuestion">Add Question</button>
</div>
<hr />
<div id="details">
    <table id="tblQuestions">
        <thead>
            <tr>
                <th>Option and Answer</th>
                <th>Question No</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

您當前的代碼會生成此代碼(請注意不良名稱屬性):

<input type="button" onclick="btnclick(this, 1);" style="display:inline-block;" class="answerBtns answers answerBtnsOff" name="value[answerF]" value="F" id="answerHRow">

請注意,名稱屬性是value[answerF]而不是您在問題中所寫的value[1][]

更新您的JavaScript,並將$newBtn行更改為:

    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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM