0

来自用户的 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 ); 
    }       
}

希望有人能帮助我解决这个问题。谢谢。

4

2 回答 2

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);
    }
}
于 2013-01-26T09:56:01.287 回答
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 ); 
    }     

}
于 2013-01-26T09:56:48.717 回答