0

我有一个循环来遍历一个数组,每个checkbox被选中的我想将值(也动态引入)放入我的QuestionSelected表中。我收到此错误"Warning: Invalid argument supplied for foreach()",无法将结果放入我的表中。这是我正在尝试的代码:

//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="question_'.$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 $id)
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
}

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

}//End of IF 'submitted
4

2 回答 2

1

The problem is that in your form, you are not using an array, but building the name values like:

name="question_'.$row['QuestionID'].'"

So $_POST["QuestionID"] does not exist and is not an array.

You can change your name building to:

name="QuestionID[]"

So that it is an array and you can even use the actual id as a key:

name="QuestionID[' . $row['QuestionID'] . ']"
于 2012-07-12T16:06:22.697 回答
0

这解决了问题并且有效:

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


}
于 2012-07-12T18:11:44.710 回答