我怎样才能得到这个SESSION值

时间:2013-01-26 09:51:43

标签: php arrays session

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

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

2 个答案:

答案 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 ); 
    }     

}