Prohibit duplicate emails in Mysql using PHP

Asked

Viewed 298 times

2

My situation is as follows, I have an email marketing system all in PHP and emails are added per file. CSV, but it is adding duplicate values and blank values.

The problem is that, i have 1 table calls n_emails with 2 columns, a call ativo and another email, the column ativo has and should have duplicated values, because it will be she who will tell if the email is active or not, IE, in virtually all emails the column value ativo will be s. The only part I want the duplicate values to be banned will be in the column email.

In short, I need to block only duplicate emails and blank emails and at the end, after adding the file. CSV, the system shows the count of added records and added records (in case duplicate emails).

Code that adds the emails is like this:

 }

 $tabela = "n_emails";
 $arquivo = 'addemail/x234gqq.csv';

 $arq = fopen($arquivo,'r');

 while(!feof($arq))
 for($i=0; $i<1; $i++){
 if ($conteudo = fgets($arq)){
 $ll++; // $ll 
 $linha = explode(';', $conteudo);// 
 }

 $sql = "INSERT INTO $tabela (ativo, email) VALUES 
 ('$linha[0]', '$linha[1]')";
 $result = mysql_query($sql) or die(mysql_error());
 $linha = array();
 }
 echo "Quantidade de Emails Adicionados: ".$ll; 
 echo "<br><a href='..'>Clique aqui para voltar</a>";

 ?>
  • 1

    Place the column email as key dish in the database.

  • just rotate ALTER TABLE n_emails ADD CONSTRAINT UNIQUE (email) in phpmyadmin itself ?

  • 1

    In theory yes and this column can not have any duplicated value, otherwise vc will need to remove them before applying the modification.

  • It worked, but when loading it shows an error screen and I’d like it to appear for example, Duplicate Emails: {n} Added Emails: {n}, how could I do it @rray ?

  • 1

    You will need two counters one for the successful Inserts and the other for the failure ones, use the function mysql_query() no if to know if the Insert worked or not, of course it will need a few more adjustments, the basic idea is this.

  • 1

    Instead of doing a disembowelment in the bank to have this behavior, why not change the application to make a select before sending the insert pro? It is a system with a low volume of data, correct? In this case 2 querys will not affect the performance.

Show 1 more comment

2 answers

7


Ensure the uniqueness of the value by adding a Unique key Constraint so the database is responsible for knowing which value is repeated or not.

ALTER TABLE tabela ADD CONSTRAINT UNIQUE (coluna)

To show the entered log count, check the result of mysql_query() and make the respective counter increment($sucesso or $falha)

$sucesso = 0;
$falha = 0;
while(!feof($arq)){
    for($i=0; $i<1; $i++){
        if($conteudo = fgets($arq)){
            $ll++; // $ll 
            $linha = explode(';', $conteudo);// 
        }

        $sql = sprintf("INSERT INTO $tabela (ativo, email) VALUES  ('%s', '%s')", $linha[0], $linha[1]);
        if(mysql_query($sql)){
           $sucesso++;
        }else{
           $falha++;
        }
        $linha = array();
    }
    echo "Resumo: Emails duplicados: $falha. Emails Adicionados: $sucesso";
    echo "<br><a href='..'>Clique aqui para voltar</a>";
}
  • 2

    Everything went right, no bugs and flaws, thanks @rray was all I was wanting and I wasn’t getting haha

2

You can add a pre-validation in php and also add Unique as quoted by @rray,

This pre-validation can be elaborated with a unique() array_and some condition validating whether the email is different from empty and active is equal to s.

Example foo.csv:

[email protected];s
[email protected];s
[email protected];s
[email protected];s
;s
[email protected];

Validating:

function getCSV($name) {
   $file = fopen($name, "r");
   $result = array();
   $i = 0;
   while (!feof($file)):
      if (substr(($result[$i] = fgets($file)), 0, 10) !== ';;;;;;;;') :
         $i++;
      endif;
   endwhile;
   fclose($file);
   return $result;
}

function getLine($array, $index) {
   return explode(';', $array[$index]);
}

$foo = getCSV('foo.csv');
$foo = array_unique($foo); // remove os repetidos
for ($i = 0; $i < count($foo); $i++) {
   $line = getLine($foo, $i);
   if (!empty($line[0]) && trim($line[1]) == 's') { // válida se tem valor e é ativo.
      print_r($line); // faça os insert's aqui
   }
}

Exit:

Array ( [0] => [email protected] [1] => s ) Array ( [0] => [email protected] [1] => s ) Array ( [0] => [email protected] [1] => s ) 
  • Now it is no longer adding the emails even in Mysql

  • @Victorgomes tried to debug to see where he stops?

  • 1

    It worked right, it was my mistake sorry, thanks @Gabrielrodrigues, your help told a lot friend, I hope you help other members of Stack also

Browser other questions tagged

You are not signed in. Login or sign up in order to post.