Handle Mysql error

Asked

Viewed 1,773 times

2

I have an insert script and would like to be able to display a custom message to the user for the following registration attempt message for an existing record:

Duplicate entry '42-1' for key 'PRIMARY'. 

I tried to use some examples like:

mysql_errno($link) e mysql_error($link)

But I could not display the result, the message does not appear, I have the following line in my code that shows the untreated message:

$aretorno["msg"] = "Ocorreu um erro na inclusão dos dados: " . $stmt->error . ". Verifique.";
$aretorno["status"] = "ERRO";

The message displayed is this:

Ocorreu um erro na inclusão dos dados: Duplicate entry '42-1' for key 'PRIMARY'. Verifique.

The write attempt code with duplicate primary key and attempt to display the treated message is this:

if ($_POST["Operacao"] == 'FaseObrigatoria') {

    $sql = "INSERT INTO gerFaseObrigatoria (IdContrato, IdTipoFase, Ordem) VALUES (?, ?, ?)";

    if($stmt = $conn->prepare($sql) ){
        $bind = $stmt->bind_param(
            "iii",          
            $_POST["IdContrato"],
            $_POST["IdTipoFase1"],
            $_POST["iOrdem"]
        );
            // EXECUTANDO A QUERY
            if($stmt->execute()){
                $aretorno["msg"] = "Registro inserido com sucesso.";
                $aretorno["par"] = $_POST["IdContrato"];
            } else {
                $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados: " . $stmt->mysql_error($conn) . ". Verifique.";
                $aretorno["status"] = "ERRO";
            }
    } else {
        $aretorno["msg"] = "Ocorreu um erro na preparação dos dados: "  . $stmt->error . ". Verifique.";
        $aretorno["status"] = "ERRO";
    }
} 

I tried to catch the mistake like this:

mysql_errno($conn) == 1451)
  • 1

    Puts the query code and how you are picking up/handling the error.

1 answer

2


When an Insert failure occurs you can send the user a generic message, when the failure is for a duplicated item (1062), take the specific sqlstate(error code) and compare within an if. mysqli_errno or $Errno do Mysqli return error code the first is for procedural style the second for object oriented.

if(!$stmt->execute()){
   if($stmt->errno == 1062){
       echo 'erro ao cadastras, essa informação já existe no banco';
   }
}

List with Mysql error codes

  • Thanks @rray, your help was excellent, problem solved.

  • 2

    That reference also helped me. TKS

  • Mysql error code list -> Page Not Found. Know where you have Mysql_i

Browser other questions tagged

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