Can anyone tell me what is causing this error

2

The email field in the database is unique

<?phprequire_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";
 }
    
asked by anonymous 02.07.2018 / 00:46

2 answers

2

As @Lite said, the problem is that you are trying to register a duplicate data in a unique row.

You can work around this by checking if the value exists 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 resulting error code. When the error is for trying to insert a duplicate data into a unique column, the generated error 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
}
    
02.07.2018 / 02:39
1

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

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

    
02.07.2018 / 01:01