如果选中,则在MySQL中输入动态创建的复选框值


Input checkbox value that is created dynamically into MySQL if checked

我从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

我理解在一条语句中插入多条记录。

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

这将把$QuestionID内的每个索引与),( 连接起来

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

INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)

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

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

通过这种方式,MySQL语句具有要插入到表中的实际值。

尝试循环您的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.")";

这将根据值的数组分配值,并将其插入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
}