-1

So I have a database with a table of movies with their respective directors. I have a form where one can add a director to a movie, but I want to not add duplicates (i.e. someone adds a director to a movie that is already in the movie director table.

I have the following, but for the life of me, I cannot figure out why this still adds the duplicate:

if (isset($_POST["submit"])) {
    $movie_id = $_POST[movie];
    $director_id = $_POST[director];
    echo $movie_id;
    echo '<br/>';
    echo $director_id;
    echo '<br/>';


    $add_sql = "INSERT IGNORE INTO MovieDirector (mid, did)
                VALUES ($movie_id, $director_id)";

    if (mysql_query($add_sql, $db_connection)){
        echo "added director to movie ";
    } 
    else { 
        echo "Failed "; 
    }
aurelius
  • 3,946
  • 7
  • 40
  • 73
Pseduosance
  • 305
  • 1
  • 5
  • 16
  • Possible duplicate of [Best way to avoid duplicate entry into mysql database](http://stackoverflow.com/questions/2219786/best-way-to-avoid-duplicate-entry-into-mysql-database) – Tim Biegeleisen Oct 30 '15 at 05:50

1 Answers1

0

I think you are confused about what the IGNORE modifier keyword does for INSERT statements in MySQL. The role of IGNORE is not to prevent duplicate records from happening, but to make errors silent.

So, there are multiple ways you could go about this:

  1. you could modify your schema to not allow duplicate records and either continue to use the IGNORE keyword, or better yet, handle theerrors

    ALTER TABLE MovieDirector ADD UNIQUE INDEX(mid, did);

  2. you could also modify your query to not insert a record if one already exists

    IF NOT EXISTS(SELECT * FROM MovieDirector WHERE mid = $movieId AND did = $directorId)
    INSERT INTO MovieDirector (mid, did) VALUES ($movieId, $directorId)
    

You probably want both of the above (probably minus the IGNORE keyword.. that's just going to come and bite you later)

This answer would be incomplete if I did not stress that you should really be using parametrized queries instead of adding the variables directly into the query string!

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • This answer would also be incomplete if we did not stress to STOP. USING. `mysql_*`!!!! It's been deprecated for some time, and outright removed in PHP7. Seriously, there's a [giant red message](http://php.net/manual/en/function.mysql-query.php) explaining this in the documentation. – maiorano84 Dec 05 '15 at 21:40