How to return Primary key error already existing in PHP / MySQL?

1

Good afternoon.

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

Follow 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 in advance for the help.

    
asked by anonymous 21.06.2018 / 21:01

1 answer

2

Use the mysqli_error() function. I use it to correct a logic error of your code, its if($inclui) will always be 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);
}
    
21.06.2018 / 23:20