简体   繁体   中英

dynamically created PHP array field not saving data in table using mysql

Hi I have a section where I am cloning a div for "Add another" button everytime it's clicked, the form fields are set as arrays. The query runs but saves nothing and just displays empty rows... can someone please tell me where could I be wrong?

<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> 

Then I save it using these lines of code:

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.'")  
        '); 
    }
}

You must loop an array before entering its values to database as follows:

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.'")  

            '); 
           }
    }
}

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM