samedi 4 mars 2017

How do I ensure the value only gets saved once into the table, when checked?

With my code here, if the user checks a check box beside one of the names the name gets saved into my review_shared table, when the user clicks 'Save'.

But I want a checked value to be only saved once into the table, the way it is now it gets saved multiple times - I mean if the user comes back to this page and the name is checked and the user clicks 'Save' again.

enter image description here

What can I add to the code for this to happen, so it will only be saved once in my review_shared table ? At present it looks like this, which saves it multiple times :

if(!empty($_POST['check_contacts'])) {
    foreach($_POST['check_contacts'] as $check) {

        //$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
            $insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";

        //we want to save the checked contacts into the review_shared table
        $insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);

    }

        //go to the main page when changes have been saved
    header('Location:volleyLogin.php');
}

    $con->close();

I thought adding code like this into the above would help, but it doesn't, really :

        if(!empty($_POST['check_contacts'])) {

    //************************* added this in **************
                $check="";
        //if the contact in review_shared is already checked, we don't want to save it multiple times
            $already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];

            $already_checked_result=mysqli_query($con,$already_checked);
            $num_rows = mysqli_num_rows($already_checked_result);

            if($num_rows >= 1) {
            echo "This is already a contact";
            break;
            }

//*******************************************************

        foreach($_POST['check_contacts'] as $check) {

            //$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
                $insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";

            //we want to save the checked contacts into the review_shared table
            $insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);

        }

            //go to the main page when changes have been saved
        header('Location:volleyLogin.php');
    }

        $con->close();




Aucun commentaire:

Enregistrer un commentaire