Search code examples
phpmysqlforeachduplicate-dataskip

skip duplicate entry in foreach mysql


hi friends i need to skip a duplicate entries in foreach and than continue on remaining ones please tell me how can i do this

foreach($arr as $key=>$arr1)
{
    echo "<pre>";

$insert=mysql_query("INSERT INTO auth_user(id,username,first_name,last_name,email,password,is_active,date_joined) VALUES('".$key."','".$arr1['username']."','".$arr1['firstname']."','".$arr1['lastname']."','".$arr1['email']."','NULL','".$arr1['is_active']."','".$arr1['date_joined']."')",$conn1);

echo $insert .'<br/>';
if($insert)
    {
        echo "DATA MIGRATE FOR USER ".$key;
        $insert1=mysql_query("INSERT INTO stylequiz_score(user_id,style_quiz_score,style_quiz_answer) VALUES('".$key."','".$arr1['style_quiz_score']."','".$arr1['style_quiz_answer']."')",$conn1);
    }
    else
    {
       echo  ("Error In MIGRATION FOR USER ".$key . mysql_error());

    }
}

Solution

  • Use the IGNORE modifier of the INSERT statement:

    $insert1=mysql_query("INSERT IGNORE INTO stylequiz_score(user_id,style_quiz_score,style_quiz_answer) VALUES('".$key."','".$arr1['style_quiz_score']."','".$arr1['style_quiz_answer']."')",$conn1);
    

    If the row being inserted would get a duplicate key error, this modifier causes the insert to be skipped with no error.