动态创建的PHP数组字段不使用mysql在表中保存数据

时间:2014-03-05 10:11:19

标签: javascript php mysql

您好我有一个部分,我每次点击时都会为“添加另一个”按钮克隆一个div,表单字段设置为数组。查询运行但不保存任何内容,只显示空行...有人可以告诉我哪里可能出错?

<label for="GCSESubject[]">GCSE Subjects</label>
<select name="GCSESubject[]" id="GCSESubject[]" style="width: 178px; float: left; margin-right: 12px;"> 
    <option value=""></option> 
    <?php echo getGCSESubjectsOptions(false, true);?> 
</select> 

然后我使用以下代码行保存它:

function saveGCSEEducation() 
{ 
    if (isset($_POST['saveGCSEEducation'])) { 

        $db = new Connection(DB_HOST, DB_USER, DB_PASS, DB_NAME); 

        $GCSESubjectSerialized = serialize($_POST['GCSESubject']); 
        $GCSESubject=mysql_real_escape_string($GCSESubjectSerialized); 
        $userID = $_SESSION['user']['userID']; 

        $db->query('
            INSERT INTO GCSEEducation 
            (userID, GCSESubject, GCSEGrade) 
            VALUES 
            ("'.$userID.'", "'.$GCSESubject.'", "'.$GCSEGrade.'")  
        '); 
    }
}

1 个答案:

答案 0 :(得分:1)

在将数据输入数据库之前必须循环数组,如下所示:

function saveGCSEEducation() 

{ 
    if (isset($_POST['saveGCSEEducation'])) { 

        $db = new Connection(DB_HOST, DB_USER, DB_PASS, DB_NAME); 
        $count= count($_POST['GCSESubject']);
        for($i=0;$i<$count;$i++)
        {
        $GCSESubjectSerialized = serialize($_POST['GCSESubject'][$i]); 
        $GCSEGradeSerialized = serialize($_POST['GCSEGrade'][$i]); 
        $GCSESubject=mysql_real_escape_string($GCSESubjectSerialized); 
        $GCSEGrade=mysql_real_escape_string($GCSEGradeSerialized); 
        $userID = $_SESSION['user']['userID']; 
        $db->query(' 

            INSERT INTO GCSEEducation 

            (userID, GCSESubject, GCSEGrade) 

            VALUES 

            ("'.$userID.'", "'.$GCSESubject.'", "'.$GCSEGrade.'")  

            '); 
           }
    }
}

希望它有所帮助!!