如何正确发布和插入值到数据库中? [英] How to post and insert values into the database correctly?

查看:296
本文介绍了如何正确发布和插入值到数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用这种格式的多维数组:value [n] [],其中n是问题编号。使用这个新的设置,您应该最终得到以下复选框字段:

 < input type =checkboxvalue = Aname =value [1] []> 
< input type =checkboxvalue =Bname =value [1] []>
< input type =checkboxvalue =Aname =value [2] []>
< input type =checkboxvalue =Cname =value [2] []>
< input type =checkboxvalue =Ename =value [2] []>

请注意,所选值在value属性中编码。 name属性只包含值所属的问题。



所以上面的输入是这样的:

 问题1:answer:A 
问题1:answer:B
问题2:answer:A
问题2:answer:C
问题2:answer:E

我想将这些细节插入问题 数据库表如下:



问题表:

  SessionId QuestionId 

MUL 1
MUL 2

答案表:

  AnswerId(auto)SessionId QuestionId答复
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 ++){

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

case3:
$ selected_option =AC;
break;

case4:
$ selected_option =A-D;
break;

case5:
$ selected_option =A-E;
break;

默认值:
$ selected_option =;
break;

}

* /当我插入网格值时需要



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

$ questionsql =INSERT INTO问题(SessionId,QuestionId)
VALUES(?,?);

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


if(!$ insert = $ mysqli-> prepare($ questionsql)){
//处理准备操作错误
}

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

$ insert-> execute();

if($ insert-> errno){
//处理此处的查询错误
}

$ insert-> close

$ insert-> insert_id;

foreach($ value as $ answer){

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

if(!$ insertanswer = $ mysqli-> prepare($ answersql)){
//处理准备操作错误
}
$ b b $ insertanswer-> bind_param(sis$ sessid,$ lastID,$ answer);

$ insertanswer-> execute();

if($ insertanswer-> errno){
//处理此处的查询错误
}

$ 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
}
}

我收到并且代码行的每个错误链接到:


警告:foreach / on line 252




  foreach($ value as $ answer){




警告:mysqli_stmt :: execute():(23000/1062):重复条目
'mul-0'for line'PRIMARY'in /.../ on line 242


上面的错误显示没有问题编号正在插入,因为它始终显示为'0'

解决方案

做的是绕过无力的皮肤复选框。我以前做过这个。



我使用跨度,因为我不确定表单域中的按钮是否会发布一个值提交表单时。我知道一个跨度不会。



在您的jsFiddle中,在 updateAnswer()函数中, )函数,您有以下代码:

  if(!bDisableAppend){
/ /将这些值附加到形式
var input ='< input type =checkboxid ='+ hid +'name =value ['+ id +']checked /& label for ='+ hid +'>'+ value +'< / label>';
_oCurrAnswerContainer.append(input);
}



在此代码中,您将设置 / code>属性为 value [answerARow] 。这是你的问题所在。



TBH,我很难跟踪你的代码,所以我想出的解决方案可能需要一些调整添加任何种类的隐藏的骗子我错过了你的例子。但这里是我想出的:



jsFiddle



<$> p $ p> var options = [A,B,C,D,E,F,G,H];


//这会将事件处理程序绑定到document元素,这样即使创建了一个新的元素,
//事件也会自动绑定到它。
$(document).on(click,span.checkbox,function(){
$(#chk+ $(this).attr(id))。 ();
$(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通过选项并将它们添加到单元格
for(var i in options)
{
$(单元格).append(
//前端覆盖复选框
$(document.createElement(span))
.addClass(checkbox unselected)
.attr(id,Value+ questionNum + options [i] )
.html(options [i])
).append(
//将发布实际值的隐藏复选框
$(document.createElement(input) )
.attr(type,checkbox)
.addClass(hidden)
.attr(id,chkValue+ questionNum + options [i])
.attr(name,value [+ questionNum +] [])
.attr(value,options [i])
);
}

//创建一个新的表行,添加选项和答案单元格
//和问题号单元格,并将其附加到表体
$(document.createElement(tr))
.append(cell)
.append($(document.createElement(td))。addClass(questionNum)。html ))
.appendTo(#tblQuestions tbody);
});

HTML

 < div id =detailsBlock> 
< button id =btnAddQuestion>添加问题< / button>
< / div>
< hr />
< div id =details>
< table id =tblQuestions>
< thead>
< tr>
< th>选项和答案< / th>
< th>问题No< / th>
< / tr>
< / thead>
< tbody>
< / tbody>
< / table>
< / div>


I want use a multi-dimensional array in this format: value[n][], where n is the question number. With this new setup, you should end up with the following checkbox fields:

<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][]">

Note that the selected value is encoded in the value attribute. The name attribute only contains the question to which the value belongs.

So what the above inputs are stating is this:

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

I want to insert these details into "Question" and "Answer" database tables below:

Question Table:

SessionId    QuestionId

MUL             1
MUL             2

Answer Table:

 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

Now I have attempted writing the mysqli/php code below to insert these values into the database but I am receiving errors and failing badly in wanting to acheive what I want to achieve. I need help being able to correctly insert the correct values in the relevant tables.

Below is the php/mysqli code:

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


}

}

}

The var_dump($_POST) outputs this below:

    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"
 } 
}

Below are the errors I am receiving and the line of code each error is linked to:

Warning: Invalid argument supplied for foreach() in /.../ on line 252

foreach($value as $answer) {

Warning: mysqli_stmt::execute(): (23000/1062): Duplicate entry 'MUL-0' for key 'PRIMARY' in /.../ on line 242

The above error shows that no question number is being inserted as it keeps displaying it as '0'

解决方案

So it looks like the main thing you're trying to do is to get around the inability to skin checkboxes. I have done this before. The way I did it was with using a span tied to a hidden checkbox.

I used spans because I'm not sure if a button in a form field will post a value when the form is submitted. I know that a span will not. This guarantees that only your checkbox value will be submitted, and not the "cover-up" value.

In your jsFiddle, in the updateAnswer() function, you have this code:

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

In that code, you are setting the name attribute of the checkbox to something like value[answerARow]. That is where your problem is.

TBH, it's kinda hard for me to follow your code, so the solution I came up with will probably need some tweaking to add whatever kind of hidden trickery I missed in your example. But here is what I came up with:

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>

这篇关于如何正确发布和插入值到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆