-1

I want to prevent the duplication of data on my database. I have two option one is for class name and the other one is class code, but every time I select same data it always insert in to the database, I want is to prevent the duplication

This is the code when button is submit

What I want is to prevent duplication of data for example student or enter and select class 1 and class code: 123, if the students enter this class 1 and class code 123 again, the student cannot enter the class because he/she was already in the class.

if($selectTheclassroomcheck > 0){ 
    $row = mysqli_fetch_assoc($selectTheclassroom);
    $insertIntoTheClassParticipant = mysqli_query($connection, "INSERT INTO teacher_class_student (teacher_class_id,student_id, teacher_id, class_id) VALUES ('".$row['teacher_class_id']."','".$_SESSION['id']."','".$row['teacher_id']."','0')");
    if($insertIntoTheClassParticipant){
        echo json_encode(1); //You are successfully enter to class
    }
    else{
        echo json_encode(2);//Incorrect class
    }
}
else{
    echo json_encode(2);

}

?>
Dale K
  • 25,246
  • 15
  • 42
  • 71
  • 1
    Please post actual code and not an image of it. You also need to tell us what isn't working the way you'd like it to, if there are any errors; given you're checking for them and I doubt you are. – Funk Forty Niner Apr 18 '20 at 03:22

1 Answers1

1

create a unique index on student_id, class, class_code (which ever columns these correspond to). When the second insert of this combination occurs a duplicate key error will occur. Catch this in your application an display an approprate error message.

Use INSERT ... SELECT to avoid your application doing this.

Also read: How can I prevent SQL injection in PHP?

danblack
  • 12,130
  • 2
  • 22
  • 41