来自用户的HTML可以选择不同类别下的主题。选定的科目后,我已将它们保存在会话中。没关系。我这样做了......
$_SESSION['select-subjectes'] = $_POST['select-subjectes'];
这是echo '<pre>', print_r($_SESSION['select-subjectes']), '</pre>';
Array
(
[Grade 5 (Scholarship Exam)] => Array
(
[0] => 3:2
[1] => 3:3
)
[Grade 11 (O/L)] => Array
(
[0] => 5:8
[1] => 5:10
)
[Graduation Level] => Array
(
[0] => 7:24
[1] => 7:46
[2] => 7:82
)
)
现在我需要将此值插入数据库。 3:2
这种值的意思是冒号前的数字是类别ID,冒号后的数字是主题ID。我的问题是当我尝试分别将这些值插入数据库时。
我试过这样的东西......但是它不起作用..
if ( isset($_SESSION['select-subjectes'])) {
$data = array();
$data = $_SESSION['select-subjectes'];
foreach($data as $key => $value) {
$pieces = explode(":", $value);
$catId = $pieces[0];
$subId = $pieces[1];
$q = "INSERT INTO category_subject ( category_id, subject_id ) VALUES ( ?, ? )";
$stmt = mysqli_prepare( $dbc, $q );
mysqli_stmt_bind_param( $stmt, 'ii', $catId, $subId );
mysqli_stmt_execute( $stmt );
}
}
希望有人帮我解决这个问题.. 谢谢。
答案 0 :(得分:1)
您的$data
数组是一个数组数组。代码中的第一个$key
是......
Grade 5 (Scholarship Exam)
...... $value
是......
Array(
[0] => 3:2
[1] => 3:3
)
......这就是它失败的原因。
使用嵌套的foreach
循环来访问您想要的元素......
foreach($data as $data_array) {
foreach($data_array as $key => $value) {
$pieces = explode(":", $value);
$catId = $pieces[0];
$subId = $pieces[1];
$q = "INSERT INTO category_subject (category_id, subject_id) VALUES (?, ?)";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'ii', $catId, $subId);
mysqli_stmt_execute($stmt);
}
}
答案 1 :(得分:1)
你必须在其上做两个foreach
循环:
foreach($data as $array){
foreach($array as $key => $value) {
$pieces = explode(":", $value);
$catId = $pieces[0];
$subId = $pieces[1];
$q = "INSERT INTO category_subject ( category_id, subject_id ) VALUES ( ?, ? )";
$stmt = mysqli_prepare( $dbc, $q );
mysqli_stmt_bind_param( $stmt, 'ii', $catId, $subId );
mysqli_stmt_execute( $stmt );
}
}