lundi 1 août 2016

Update checkbox value in database with same name

I have checkboxes with the same name and the first insert works fine. Next time, when I want to update the values, it creates new rows.

I have two tables: education_levels and user_educations.

user_educations

id | user_id | education_id
1    83        1
2    83        2

education_levels

education_id | education
1              Middle school
2              High school
3              Bachelor’s degree
4              Master’s degree

..etc

How can I update only the checkboxes, which were checked and those that are not checked, change the value to 0. I am using PHP and ajax/jquery to post.

HTML

<div class="form-group form-group-custom" id="checkboxes">
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Üldharidus" name="userEducationDegree[]" value="5">
        <label for="Üldharidus"> Üldharidus </label>
    </div>
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Kutseharidus" name="userEducationDegree[]" value="6">
        <label for="Kutseharidus"> Kutseharidus </label>
    </div>
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Kõrgharidus" name="userEducationDegree[]" value="4">
        <label for="Kõrgharidus"> Kõrgharidus </label>
    </div>
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Alusharidus" name="userEducationDegree[]" value="1">
        <label for="Alusharidus"> Alusharidus </label>
    </div>
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Põhiharidus" name="userEducationDegree[]" value="3">
        <label for="Põhiharidus"> Põhiharidus </label>
    </div>
    <div class="checkbox checkbox-inline">
        <input type="checkbox" id="Keskharidus" name="userEducationDegree[]" value="2">
        <label for="Keskharidus"> Keskharidus </label>
    </div>
</div>

PHP

        if(isset($_POST['userEducationDegree']) && !empty($_POST['userEducationDegree'])){
            $userEducationDegree = $_POST['userEducationDegree'];

            for ($i = 0; $i < count($userEducationDegree); $i++) {
                $user_education = $user_home->runQuery("INSERT into user_education (id, user_id, education_id) 
                VALUES (:education_experience_id, :user_id, :education_id) ON DUPLICATE KEY UPDATE user_id= VALUES(user_id), education_id= VALUES(education_id)");
                $user_education->bindparam(':user_id', $user_id, PDO::PARAM_STR);
                $user_education->bindparam(':education_id', $userEducationDegree[$i], PDO::PARAM_STR);
                $user_education->execute();
            }
        }else{
            $errors++; 
            $errors_query["status"] = 'error';
        }

I know I could give them seperate names, but I have to use same name, so in validation at least one of the options is selected.




Aucun commentaire:

Enregistrer un commentaire