0

我正在从 MySQL 中的问题表中提取问题并以表格形式填充它们。这工作正常,我正在填充复选框,并且该值是用 QuestionID 填充的。该数组已正确填充,但我想获取选中复选框的值(这是我的问题 ID)并将该 ID 插入到表中,以便我有选择的问题供其 ID 使用。这是我到目前为止所拥有的:

//Declare the QuestionID as a array
$QuestionID = array();


while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name=chkQuestion align="left"/><p>' . $row['Question'] .'</p></div><br/><br/>';

//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];

}


if($_POST['submitted']) { 


if (isset($_POST['chkQuestion']))
{
//create the query for the score
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES ($QuestionID)"; 

//Run the query 
$run2 = @mysqli_query ($conn,$sql2);

//Confirm message data was entered with a correct response and a graphic
echo '<h1>Submitted!!</h1>';

}


}//End of IF 'submitted
4

4 回答 4

0

尝试循环您的 ID 并逃脱它!

    $ids_list = '';
    foreach($_POST["chkQuestion"] as $id)
    {
        $ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
    }

    $sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
于 2012-07-12T13:49:17.627 回答
0

你想在一个语句中插入多条记录是我的理解。

$sql2 = "INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(". implode('),(', $QuestionID) . ")";

$QuestionID这将在里面加入每个索引),(

如果你要回声$sql2,你会得到

INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)
于 2012-07-12T13:46:25.367 回答
0

您可以使用循环来获取检查的问题。

for($i=0;$i<count($_POST["chkQuestion"]);$i++) {
  "INSERT INTO tbl_QuestionSelected (QuestionID) VALUES('".$_POST["chkQuestion"][$i]."');
}

这样,MySQL 语句就有了要插入到表中的实际值。

于 2012-07-12T13:51:51.977 回答
0

这将根据值的数组分配值并将其插入 MySQL:

//Declare the QuestionID as a array
$QuestionID = array();


while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name="QuestionID[' . $row['QuestionID'] . ']">' .$row['Question']. '</p></div><br/><br/>';

//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];

}

if($_POST['submitted']) { 


$ids_list = '';

foreach($_POST["QuestionID"] as $key=>$value) {
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($value);
}

$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";

//Run the query 
$run2 = @mysqli_query ($conn,$sql2);


}//End of IF 'submitted
}
于 2012-07-12T18:08:43.477 回答