We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

Abe on 01/29/08


Tagged

mysql database duplicate rows


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

naz


Remove Duplicate Rows


Published in: PHP 


$duplicates checks and groups duplicated rows with the same field1 and field2 (like comments maybe) and $limit counts how many times a row is duplicated.

  1. <?php
  2. $duplicates = mysql_query("SELECT field1, field2, count(*) FROM table GROUP BY field1, field2 having count(*) > 1");
  3. $count = mysql_num_rows($duplicates);
  4. if ($count > 0) {
  5. while ($row = mysql_fetch_assoc($duplicates)) {
  6. $field = $row["field1"];
  7. $limit = $row["count(*)"] - 1;
  8. mysql_query("DELETE FROM table WHERE field1='$field' LIMIT $limit");
  9. }
  10. mysql_free_result($duplicates);
  11. }
  12. ?>

Report this snippet 

You need to login to post a comment.