How to Return Existing Primary Key Error in PHP/Mysql?

Asked

Viewed 90 times

1

Good afternoon.

How to return an error when there is an attempt to insert a row into a table, and the primary key already exists? By default, the database does not insert the line. How to display this error as "Existing item"?

Follows part of the code:

$mysqli = new mysqli('localhost', 'root', '', 'datalin');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$inclui="INSERT INTO DTC (DTC_CDRDES,DTC_CGC,DTC_TIPDOC,DTC_NUMNFC,DTC_QTDVOL,DTC_DATREC,DTC_PROCES,DTC_FORNEC) VALUES ('$CDRDES','$CNPJ','$TipDoc','$NumNFC','$QTDVol','$DataRec','$proces','$FORNEC')";

mysqli_query($mysqli,$inclui);

if($inclui):
    echo "<script>
                alert('Usuario Incluido com sucusso. :D');
                window.location='index.php';
        </script>";
else:
    echo "<script>
            alert('Infelizmente não foi possível excluir. :C');
            window.location='index.php';
        </script>";
endif;//echo "Cadastro realizado com sucesso!<br>Agradecemos a atenção.";

mysqli_close($mysqli);

Thanks for your help.

1 answer

2


Use the function mysqli_error(). I take this opportunity to correct a logic error of your code, your if($inclui) will always turn out true.

$sql="INSERT INTO DTC (DTC_CDRDES,DTC_CGC,DTC_TIPDOC,DTC_NUMNFC,DTC_QTDVOL,DTC_DATREC,DTC_PROCES,DTC_FORNEC) VALUES ('$CDRDES','$CNPJ','$TipDoc','$NumNFC','$QTDVol','$DataRec','$proces','$FORNEC')";

// mysqli_query retorna false se falhar
$sucesso = mysqli_query($mysqli, $sql);

if(!$sucesso) {
    echo mysqli_error($mysqli);
}
  • Thanks for the reply. It worked by putting if($success) without the "!".

  • The ! is a denial. Without this, you will enter the if when the query runs smoothly. With the exclamation, you only enter when a problem occurs (which can be a primary key violation, you need to look at the error message to be sure).

Browser other questions tagged

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