INSERT duplicate with mysql :: PDO

1

Can anyone explain why when I run this code it INSERT twice the same value in the table?

I believe that this problem happens when I do a validation to verify that the values have been entered: if(!$lc_follow_dados->execute())

        $method     = $_POST['method'];
        $id_de  = $_POST['id_de'];
        $id_para    = $_POST['id_para'];
        $f_data     = time(); 

        if($method == 'add'){
            $busca_dados_s = $pdo->prepare("SELECT * FROM 'lc_follow' WHERE 'f_de' = ? AND 'f_para' = ?");
            $busca_dados_s->execute(array($id_de, $id_para));
            if($busca_dados_s->rowCount() == 0){
                $lc_follow_dados = $pdo->prepare("INSERT INTO 'lc_follow'(f_de,f_para,f_data)VALUES(:f_de,:f_para,:f_data)");
                $lc_follow_dados->bindValue(":f_de",$id_de);
                $lc_follow_dados->bindValue(":f_para",$id_para);
                $lc_follow_dados->bindValue(":f_data",$f_data);
                $lc_follow_dados->execute();

                if(!$lc_follow_dados->execute()) { 
                    echo '::ERRO::';
                } else {
                    echo    '<div class="but_add" onclick="functionAjax_follow(\''.$id_de.'\', \''.$id_para.'\',\'remove\')">
                                <i class="glyphicon glyphicon-ok"></i>
                                Seguindo
                            </div>';
                }
            }
        }
    
asked by anonymous 10.02.2016 / 15:34

2 answers

2

When calling the execute() method of the PDO it executes the query contained in that prepared statement, its code has two calls. Remove the first occurrence

 $lc_follow_dados->execute();

 if(!$lc_follow_dados->execute()) { 
    
10.02.2016 / 15:50
1

Exactly when you enter "if" it re-runs the corresponding sql:

  • First call: $ lc_follow_dates-> execute ();

  • Second Call: if (! $ lc_follow_dados-> execute ())

Just remove the first call.

    
11.02.2016 / 18:47