Remove duplicate entries from php mysql database

To remove duplicate entries from php mysql database based on a fieldname you have to use some combination of sql queries. The idea is to select all ids of unique emails and then delete the rest apart from those ids. Here is a working code snippet

The first query is used to select ids of the row with GROUP BY clause. The second query deletes all other rows apart from those collected ids with NOT IN clause.

  $ids       = array();
  $query     = "SELECT id FROM emails GROUP BY email";
  $result    = mysql_query($query);
  while($row = mysql_fetch_assoc($result)){
      $ids[] = $row['id']; 
  }
 
  mysql_query("DELETE FROM emails WHERE id NOT IN (".implode(",", $ids).")"); 

Remove duplicate entries from php mysql database Remove duplicate entries from php mysql database Reviewed by JS Pixels on July 16, 2011 Rating: 5

4 comments:

  1. thank you so much for this code!!!
    I am a very new beginner to php and my programmer simply disappeared leaving me helpless with a duplicate sql fields bug...
    thanks to you I have fixed this !

    ReplyDelete
  2. Great Blog, Thank you so much for the code. God Bless.

    ReplyDelete
  3. Thanks you so much!
    It's save my much time.

    ReplyDelete
  4. Great solution. It has solved all my problems.
    Thanks a lot.

    ReplyDelete

Altaf Web. Powered by Blogger.