Search code examples
phpmysqlarraysunique-constraintdistinct-values

PHP/MySQL Insert distinct array values


I am inserting values into a MySQL table using the code below, and I need to prevent users from inserting the same priority value for each studentname more than once. What is the best way to do this please?

This is the table:

 id         studentname    title         academicdiscipline  priority    
012345678   TEST, NAME     Test title 1     Civil                1
012345678   TEST, NAME     Test title 2     Civil                2
012345678   TEST, NAME     Test title 3     Civil                3
012345678   TEST, NAME     Test title 4     Civil                4
012345678   TEST, NAME     Test title 5     Civil                5

Code:

if(isset($_POST['submit']) && !empty($_POST['submit'])) {
  $ids = $_POST['id']; 
  $names = $_POST['studentname']; 
  $titles = $_POST['title'];  
  $disciplines = $_POST['academicdiscipline']; 
  $priorities = $_POST['priority']; 

foreach($priorities as $key => $priority) { 
    if ($priority > 0) { 

        $query = "INSERT INTO flux_project_selection (id, studentname, title, academicdiscipline, priority) 
            VALUES ( " . mysql_real_escape_string($ids[$key]) . ",
            '" . mysql_real_escape_string($names[$key]) . "',
            '" . mysql_real_escape_string($titles[$key]) . "',
            '" . mysql_real_escape_string($disciplines[$key]) . "',
            " . mysql_real_escape_string($priority) . "  )";

         $retval = mysql_query($query) or die(mysql_error()); 
                            } 
                        } 
                echo "<p> Added.</p><br />"; 
} 

Solution

  • Create index for unique record, using combination of fields

    ALTER TABLE table_name ADD UNIQUE INDEX index_name (field1, field2);
    

    it will allow you to add first record but on duplicate entry show Duplicate entry ... for unique index. You can either use try and catch to display error message or use on duplicate update record if your project has this requirement.