简体   繁体   English

努力将值正确插入数据库

[英]Struggling to insert values correctly into database

I want use a multi-dimensional array in this format: value[n][], where n is the question number. 我想使用这种格式的多维数组:值[n]的[],其中n是问题编号。 With this new setup, you should end up with the following input fields: 使用此新设置,您应该最终得到以下输入字段:

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

Note that the selected value is encoded in the value attribute. 请注意,所选值被编码在value属性中。 The name attribute only contains the question to which the value belongs. name属性仅包含值所属的问题。

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. 现在,我尝试编写下面的mysqli / php代码以将这些值插入数据库,但是我收到错误,并且在实现自己想要达到的目标方面失败。 I need help being able to correctly insert the correct values in the relevant tables. 我需要能够在相关表中正确插入正确值的帮助。

Below is the php/mysqli code: 以下是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 = implode(':', $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();

        $lastID = $id->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: 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(1) "A" 
  ["answerCRow"]=> string(1) "C" 
  ["answerBRow"]=> string(1) "B" 
  ["answerERow"]=> string(1) "E" }
}

Below are the errors I am receiving and the line of code each error is linked to: 以下是我收到的错误以及每个错误链接到的代码行:

Warning: implode(): Invalid arguments passed in /.../ on line 226 警告:implode():无效的参数在第226行的/.../中传递

$answer = implode(':', $value);

Notice: Trying to get property of non-object in /.../ on line 250 注意:试图在第250行的/.../中获取非对象的属性

$lastID = $id->insert_id;

Warning: Invalid argument supplied for foreach() in /.../ on line 252 警告:第252行的/.../中为foreach()提供了无效的参数

foreach($value as $answer) {

Warning: mysqli_stmt::execute(): (23000/1062): Duplicate entry 'MUL-0' for key 'PRIMARY' in /.../ on line 242 警告:mysqli_stmt :: execute():(23000/1062):/ 242 /行中的/.../中的键“ PRIMARY”的条目“ MUL-0”重复

The Above Error Points to the $insert query 上面的错误指向$insert查询

MORE INFO: 更多信息:

The structure I really want to acheive after posting the text inputs is below: 发布文本输入后,我真正想要实现的结构如下:

array(2) { 
            ["numQuestion"]=> array(2) { 
                                        [0]=> string(1) "1" 
                                        [1]=> string(1) "2" 
                                       }
           ["submitDetails"]=> string(14) "Submit Details" 
           ["1"] => array(2) {
                                        [0] => string(1) "A"
                                        [1] => string(1) "C"
                                      }
           ["2"] => array(2) {
                                        [0] => string(1) "A"
                                        [1] => string(1) "B"
                                        [2] => string(1) "E"
                                      }
        }

When the user posts the text input values, it should insert the question numbers and the answers which belongs to their relevant question number. 用户发布文本输入值时,应插入问题编号和属于其相关问题编号的答案。

A few things: 一些东西:

  1. $result / $_POST['value'] is a one-dimensional array, so $value in your foreach loop is a string that you cannot use implode on; $result / $_POST['value']是一维数组,因此在foreach循环中的$value是一个字符串,不能implode进行内implode
  2. $lastID = $id->insert_id; should be $insert->insert_id and I'm not sure if you can close the connection already before you call that statement; 应该是$insert->insert_id ,我不确定在调用该语句之前是否可以关闭连接;
  3. $value is a string (see first point) so you cannot use foreach there (third warning). $value是一个字符串(请参阅第一个要点),因此您不能在那里使用foreach (第三个警告)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM