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

时间:2012-07-12 13:42:56

标签: php

我从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 个答案:

答案 0 :(得分:0)

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

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

这会将$QuestionID内的每个索引与),(

连接起来

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

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

答案 1 :(得分: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.")";

答案 2 :(得分:0)

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

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

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

答案 3 :(得分: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
}