Compare form domain with database domain

Asked

Viewed 407 times

1

I need to compare domain sent and processed by a form via $_POST with domains of the database because I can only enter one email from each domain in the database. For this first I took the email from $_POST and then stored all the base emails in an array with mysql_fetch_array at the bank. Now, I need to get this array return only domains as I did with explode which resulted in variable $tmpdominio and then compare these two information to see if the domain already exists in the bank. As I am starting, so far I have this code.

# Pegando o dominio deste email
$emaildoform    = $_POST['email'];
$tmpdominio     = explode('@', $emaildoform);

# Pegando todos os emails da minha tabela
$dados      = mysql_query("SELECT email FROM wp_agencias");

while($arraydeemails = mysql_fetch_array($dados)){

    # Eu preciso extrair o domínio de cada e-mail do array ...
    # ... depois vou comparar com $tmpdominio para ...
    # ...verificar se dominio está presente na base

};
  • Have you ever tried to set the email field as unique in the bank? you can only have an email with the same domain in your bank?

  • Have you tried using the in_array()

  • 1

    Instead of bringing all the data from the database, why not use the like in your query to search for email with that domain? If you return any results, it is because the email exists in the database.

  • @Filipe is that in another answer of those days, "they taught" him to use this thing of storing db in array unnecessarily. What is spent for nothing in memory, because even in that other one, you could use Mysql’s "save result" if you needed to keep the data. The funny thing about the other question is that the owner of the complicated answer erroneously said that the others were wrong, and even took the Accept :)

  • @Bacco because, the query should return the smallest possible result and using array is not always the best solution.

3 answers

3


Perhaps the solution meets your need, then you will have a good idea of what can be done. Success!

if (isset($_POST['email'])){
   // Recuperando domínio do e-mail recebido pelo form
   $dominio = explode( '@', $_POST['email'] );

   // Pegando todos os emails da minha tabela
   $dados = mysql_query("SELECT email FROM wp_agencias WHERE email LIKE @".$dominio[1]);

if( $dados) {
   echo "Domínio ". $dominio[1]." já cadastrado";
} else {
   echo "Domínio ". $dominio[1]." não cadastrado";
}
}
  • Very good your code!!! Thank you.

  • Do not use content originating from a form directly in an SQL query. Use mysql_real_escape_string() or Prepared statements.

2

// Extrai apenas o dominio do e-mail.
$dominio = explode('@', $_POST['email']);
$dominio = $dominio[1];

// Torna a string segura para uso em consultas.
// (Evita SQLInjection).
$dominio = mysql_real_escape_string($dominio);

// Consulta se o dominio já existe.
$dados = mysql_query('SELECT email FROM wp_agencias WHERE email LIKE "%@'.$dominio.'"');

if (mysql_num_rows($dados)>0) die("Dominio já existe");
else
{
    // Torna a string segura para uso em consultas.
    $email = mysql_real_escape_string($_POST['email']);

    // Insere no banco de dados.
    mysql_query('INSERT INTO wp_agencias(email) VALUES ("'.$email .'");');
}
  • Very good your code !!!

  • There was a little mistake, I just corrected.

1

First I would like to know if this mailing list is too big. If it is, it may give you performance problems. But I will talk about two options. If your list is small this gist here can help you solve:

<?php
class DomainCheck {
    private $email;

    function __construct($email_a_verificar) {
        $this->email = $email_a_verificar;
    }

    private function getDominio($email) {
        $email = explode('@',$email);
        return $email[ count( $email ) - 1 ];
    }

    function check($lista_de_emails) {
        $dominio_a_verificar = $this->getDominio( $this->email );

        foreach( $lista_de_emails['email'] as $email ) {
            $dominio_atual = $this->getDominio( $email );

            if ( $dominio_a_verificar == $dominio_atual ) {
                throw new Exception("Domínio existente na lista", 1);
            }
        }
    }
}

//a lista simula o seu recordset
//usando um fetchAll do PDO
$lista_emails_do_banco = array(
    'email'=>array(
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]'
    )
);

$email_recebido_do_form = '[email protected]';

$check = new DomainCheck($email_recebido_do_form);
try {
    $check->check( $lista_emails_do_banco );
    echo "Sem duplicações de e-mail";
    //Rotina de salvamento do registro pode vir aqui
} catch( Exception $e ) {
    echo $e->getMessage();
}

https://gist.github.com/evaldobarbosa/c302b2d1c327a0708735

But if your list is muuuuuuuito large, then you can add a field for the domain in the table with the emails and then search for the domain field.

  • 1

    Prefer to add the code to the question itself instead of using an external system. So we can keep the code always available here and the answer remains valid.

Browser other questions tagged

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