Can anyone tell me what is causing this error

Asked

Viewed 131 times

2

the email field in the database is Unique

inserir a descrição da imagem aqui

    <?php
require_once("conexao.php");
$nome  = $_REQUEST['nome'];
$email =$_REQUEST['email'];
$telefone = $_REQUEST['telefone'];

 try{
 $conexao = new PDO($banco,$user,$senha);
     $sql = "INSERT INTO tb_crud2 (nome,email,telefone) VALUES ('$nome','$email','$telefone')";
     $registro = $conexao->query($sql);

     $row = $registro->rowCount();
  if ($row==1){
      echo "cadastrado com sucesso";
  }else{
      echo "este email já está cadastrado em nosso banco de dados";
  }
 }catch (PDOException $e){
     echo "erro ao se conectar";
 }

2 answers

2

As @Leite said, the problem is that you are trying to record a duplicate data in a Row unique.

You can get around this by checking if there is value before:

$conexao = new PDO($banco,$user,$senha);
$registro = $conexao->query("SELECT * FROM tb_crud2 WHERE email = '$email'");

if ($registro->fetchColumn() == 0) //Email não cadastrado
{
    //Código do insert, etc
}
else //Email duplicado
{
    echo "este email já está cadastrado em nosso banco de dados";
}

Or check the code of the resulting error. When the error is by trying to insert duplicated data into a Unique column, the error generated has the code 1062:

$conexao = new PDO($banco,$user,$senha);
$registro = $conexao->query("INSERT INTO tb_crud2 (nome,email,telefone) VALUES ('$nome','$email','$telefone')");

if (!$registro && $conexao->errorCode() == '1062') //Retornou erro de dado duplicado
{
    echo "este email já está cadastrado em nosso banco de dados";
}
else
{
    //Código do insert, etc
}
  • Bad solution using select. Unique is just to avoid having to do this check first, so there’s no reason to do it. Analyze the return of the Insert and, if necessary, the error code, is the best and only it would be enough to answer.

  • Ah, just gave as option, also do not like the option of select pq can have problems with competition. msm email can be inserted between select and Insert.

1

Your query must be returning false, which is what the PDO::query returns when the query fails, if it was working, it should return a PDOStatement, that does not happen there.

The problem may be the email being repeated if it is unique in the database, but with the information of the question, this seems to be the most likely cause.

  • that’s right, when the email does not exist in the BD and normal registration, but when it already exists it gives this error, because it was to return 0 and with that run the Else block, but I do not know why it gives this error.

Browser other questions tagged

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