Form recording the same data

Asked

Viewed 95 times

1

Good afternoon guys. I have a problem that I can’t find a solution.

I made a form to record the registrations of a web site , but often this being saved the same registration several times (see print)

Print banco de dados I validated the entire form not to risk giving any , but I can not solve this problem, below follows the code for registration

UPDATE ---

Below , follows the code practically complete , I only removed the form code and part of the code that assembles the body of the sent email , not to get too big.

class compra_onlineController extends baseController
{

    public function index()
    {   
        $args = func_get_args();

        if (isset($args[0]) && $args[0] == 'nobanner')
            $vars['arg'] = $args[0];
        else
            $vars['arg'] = 'banner';

        if (defined('CANONICAL'))
            $vars['canonical'] = CANONICAL;

        $this->visitCheck();

        new Load('index', $vars);
    }

    public function assinar()
    {   
        $args = func_get_args();

        if(isset($args[0]))
                $vars['arg'] = $args[0];
                $package = new PackageModel();

                $package->selectById((int) $vars['arg']);

       $vars['text'] = $package->getHtml().' 

        //aqui fico o código do formulario ///

 //fim formulario ';


        if ( isset($_POST['txtNome']) && $_POST['txtNome'] != '' &&
            isset($_POST['txtTel1']) && $_POST['txtTel1'] != '' &&
            isset($_POST['txtEmail']) && $_POST['txtEmail'] != ''
            ) {

                    require_once(SITE_PATH.'inc/phpmailer/class.phpmailer.php');


            //codigo que monta corpo email
            $message_html .= '<b>Nome:</b> '.$_POST['txtNome'].'<br>';
            $message_html .= '<b>Sexo:</b> '.$_POST['txtSexo'].'<br>';

            $message_html .= '<b>CPF:</b> '.$_POST['txtCpf'].'<br>';
            $message_html .= '<b>RG:</b> '.$_POST['txtRg'].'<br>';

            ....



            /* --------------------------------- */


             //codigo que monta corpo email
            $message_txt .= '<b>Nome:</b> '.$_POST['txtNome'].'<br>';
            $message_txt .= '<b>Sexo:</b> '.$_POST['txtSexo'].'<br>';

            $message_txt .= '<b>CPF:</b> '.$_POST['txtCpf'].'<br>';
            $message_txt .= '<b>RG:</b> '.$_POST['txtRg'].'<br>';

            $message_txt .= 'Por favor, não responda este e-mail.'."\r\n";

            .......

            $mail = new PHPMailer();

            try {
                $mail->addAddress(EMAIL, 'Contato');
                $mail->Subject = $subject;
                $mail->msgHTML($message_html);
                $mail->AltBody = $message_txt;
                $mail->send();
                if($mail->send()){
                    $vars['script'] = "window.location.href='".SITE_HTTP.PREF_HOST.SELF_PATH."controllers/obrigado_2.html'; "; //Nessa pagina , obrigado_2.html , tem os códigos de conversão do GOOGLE ADWORDS  , Bing Ads e Facebook Ads , nela também é feito o redirecionamento.

                }

                $this->visitCheck(true);
            } catch (phpmailerException $e) {
                echo $e->errorMessage(); //Pretty error messages from PHPMailer
            } catch (Exception $e) {
                echo $e->getMessage(); //Boring error messages from anything else!
            }
        }
        else {

            $this->visitCheck();
        }

        if (defined('CANONICAL'))

            $vars['canonical'] = CANONICAL;

        new Load('compra_online', $vars);
    }


function inserir_contato($pdo,$corrige){

    try {

        $arr = array();

        $sql = 'INSERT INTO contatos(telefone)VALUES(:telefone)';
        $stmt = $pdo->prepare($sql);
        $dados = array(

                    ':telefone' => str_replace($corrige, "", $_POST['txtTel1'])
                );

        $stmt-> execute($dados);
        $linha = $stmt->rowCount();
            if($linha == 1){

                return $stmt = $pdo->lastInsertId();
                $pdo = null;

            }else{

               return 0;
            }



    } catch(Exception $e) {

        print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

    }

}

function inserir_contato_nome($pdo,$id_contato){

    try {

            $arr = array();  
            $sql = 'INSERT INTO contato_dados_nome(id_contato,nome)VALUES(:id_contato,:nome)';
            $stmt = $pdo->prepare($sql);
            $dados = array(

                ':id_contato'=> $id_contato,
                ':nome' => $_POST['txtNome']
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{

                    $arr['retorno'] = 0;
                }



        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

function inserir_contato_dados($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $data = explode("/",$_POST['txtData_nasc']);

            $data_nasc = $data[2]."-".$data[1]."-".$data[0];


            $sql = 'INSERT INTO contato_dados_principal(id_contato,tipo_contato,data_nascimento,sexo,telefone_2)
                                VALUES
                                (:id_contato,:tipo,:data,:sexo,:telefone_2)';
            $stmt = $pdo->prepare($sql);
            $dados = array(
                ':id_contato' => $id_contato,
                ':tipo' => 'fisica',
                ':data'=> $data_nasc,
                ':sexo' => $_POST['txtSexo'],
                ':telefone_2' => str_replace($corrige, "", $_POST['txtTel2'])
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{
                    $arr['retorno'] = 0;
                }


        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}


function inserir_contato_pessoa_fisica($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $sql = 'INSERT INTO contato_pessoa_fisica(id_contato,rg,cpf)VALUES(:id_contato,:rg,:cpf)';
            $stmt = $pdo->prepare($sql);
            $dados = array(
                ':id_contato' => $id_contato,
                ':rg' => str_replace($corrige, "", $_POST['txtRg']),
                ':cpf' => str_replace($corrige, "", $_POST['txtCpf'])
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{

                    $arr['retorno'] = 0;
                }


        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

function inserir_contato_endereco($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $sql = 'INSERT INTO contato_endereco(id_contato,tipo,cep,rua,numero,bairro,cidade,uf)
                                VALUES  (:id_contato,:tipo,:cep,:rua,:num,:bairro,:cidade,:uf)';

            $stmt = $pdo->prepare($sql);
            $dados = array(

                    ':id_contato' => $id_contato,
                    ':tipo' => $_POST['txtTipo_endereco'],
                    ':cep' => str_replace($corrige, "", $_POST['txtCep']),
                    ':rua' =>$_POST['txtRua'],
                    ':num' => $_POST['txtNumero'] ,
                    ':bairro' => $_POST['txtBairro'],
                    ':cidade' => $_POST['txtCidade'],
                    ':uf' => $_POST['txtEstado']
                );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{
                    $arr['retorno'] = 0;
                }


        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}


if(isset($_POST['enviar'])){


    $corrigir = array(' ','-','(',')','.');

    $contato = new compra_onlineController();
    $conexao = $contato->fn_conexao();
    $id = $contato->inserir_contato($conexao,$corrigir);
    $contato->inserir_contato_nome($conexao,$id);
    $contato->inserir_contato_dados($conexao,$id,$corrigir);
    $contato->inserir_contato_pessoa_fisica($conexao,$id,$corrigir);
    $contato->inserir_contato_endereco($conexao,$id,$corrigir);
}

EDIT --

Required page_2.html

//codigo do adwords
//codigo bing

<body>
    <script>
        alert('Obrigado pelas informações.Qualquer dúvida ligue grátis ou fale conosco através de nosso chat.');
        window.location.href="http://site.com.br";
    </script>

</body>

Why is the same registration inserted several times ? I find it difficult to be the user because it happened several times .

Thanks in advance.

2 answers

4

Hi. Changes the field telefone for UNIQUE. So you will no longer have duplicate data.

ADD UNIQUE INDEX `telefone`

Whenever you try to register another mobile phone with the same digits, the query will fail.

Or, make a redirect, for when you register this value, so you will not have to resend the same form twice.

header("Location: formulário.php");
exit;
  • Good afternoon Aura , then , the problem is that I record in the phone table both the registration data of the website and the links that the company receives. If I leave as Unique the phone field , if the person calls here and then to make a registration , will give error , because the phone would already be in the database .

  • @Henriquefelix You can redirect the user when you enter the value.

  • Good afternoon, I already do the redirect hehe . I will edit the question and put the rest of the code for you to see .

  • Still the same code.

  • I added the code of the full page , I only omitted the code of the form

  • 1

    You didn’t show where you’re redirecting.

Show 1 more comment

2


Make sure the user is not giving doubleclick on the button and the same is firing several times the same action, I’ve seen a lot of it.

Do a test, create a script that after the first click disable the button, and see how it behaves.

  • Good afternoon @Rboschini , had already thought of something like , but when one clicks on the Ubmit button , it triggers a script that validates the form , if there is an error , the button gets disabled and then the person will not be able to send again .

  • Have you tested by filling all the fields and clicking several times, if you are slow after clicking 1x, the button is really disabled? if the user gives ENTER in some field and the form is with correct data, it does not from the other Ubmit not? .

  • Good afternoon. Pressing enter sends yes , but the fields are validated ,if they are not filled or the size they should have ( ex: Cpf has to have 11 characters in the field) , gives a js alert and does not send the form.

  • Good afternoon @Rboschini , I did the test of pressing several times the Submit button ,and I saw that the system became slow ,where every time I pressed it increased even more the loading , until it gave timeout on the page. I believe that the problem should be right there , how to proceed ?

  • Do so, create a variable, and when you give Ubmit arrow this variable to true, and let pass in suibmit only when this variable is false. must resolve.

  • I did so : $key = false; if($key == false){ if(isset($_POST['send'])){ $correct = array(' ','-','(',')','.'); $contact = new compra_onlineController(); //rest of the code $key = true; } } . But it didn’t work . =(

  • Do this in javascript not in PHP. It has to be where you give your $('form'). Submit(). The goal is not to let it give Ubmit more than 1x, it has to be in client-side.

  • Good night @Rboschini , was barely gone ( trampo ) , It worked out the way you recommended. Put an answer showing the solution or milestone here as a solution ? From now on, grateful

  • Mark here as a solution, then I help you and you help me! Glad it worked, what a thing to call. abracos

Show 4 more comments

Browser other questions tagged

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