Question

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());

    }
}
Was it helpful?

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.

OTHER TIPS

array_unique will remove all the duplicate values in the array. In your case, try like this.

$arr = array_unique($arr);

You don't need to do any extra functions.

Assuming that you have duplicate values in $arr

use array_unique

$res_array = array_unique($arr);

ref: http://php.net/manual/en/function.array-unique.php

To check duplicate in databse, put your insert query in if condition

$sql   = mysql_query("SELECT * FROM auth_user WHERE email = '".$arr1['email']."'");
if(mysql_numrows($sql) == 0){
   $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);
}
else{
   $insert = false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top