INSERT duplicate with mysql ::PDO

Asked

Viewed 111 times

1

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

I believe it is that this problem happens when I do a validation to check if the values were 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>';
                }
            }
        }

2 answers

2

When calling the method execute() of PDO it executes the query contained in that Prepared statement, in your code you have two calls. Remove the first occurrence

 $lc_follow_dados->execute();

 if(!$lc_follow_dados->execute()) { 

1

Exactly, when you enter the "if" it runs again the corresponding sql:

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

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

Just remove the first call.

Browser other questions tagged

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