Page 1 of 1

ckecking for duplicates when loading file to mysql?

Posted: Sun Feb 08, 2009 6:45 pm
by arya6000
How about this?

Code: Select all

<?php
mysql_connect("....", ".....", "......");
mysql_select_db("....");
$i = 0;
$handle = @fopen("name1.csv", "r");
if ($handle) 
{
    while (!feof($handle)) 
    {
        $buffer = fgets($handle, 4096);
        $res = mysql_query("SELECT `name` FROM  `names` WHERE `name`='$buffer'");
        if(mysql_num_rows($res)==0) {
                mysql_query("INSERT INTO names(name, child) VALUES('$buffer','no')"); 
                $i++;
        }
    }
    fclose($handle);
}
else
{
echo "File did not open";
}
echo $i;
echo " imported";
?> 
You could also just create a unique index on the name field of the table, which would prevent any duplicates from being accepted.