当用户从Oracle在PHP应用程序中输入重复的主键时,引发应用程序错误

I'm not sure where to start to raise an error in my php app from oracle. I need to raise an error whenever the user (which would be us here) enters a duplicate primary key, foreign key violation or even not null values. The thing is, i'm not sure where to start, do i need to use a trigger here ?

Look at the code below, i think i'm almost there but i'm not sure what to do from now on. This is just the code for my primary key error. Of course, i assume that if i can make this one work, the others error should not be too hard to code after that

create or replace trigger TRG_PRIMARY_KEY_TYPE_ENCAN
    before insert or update on TP2_TYPE_ENCAN

declare

    cursor PRIM_KEY is
    select CODE_TYPE_ENC FROM TP2_TYPE_ENCAN;
    V_CODE_TYPE_ENCAN char(2);

begin
    select CODE_TYPE_ENCAN into V_CODE_TYPE_ENCAN from TP2_TYPE_ENCAN;
    for V_CODE in PR_KEY 
    loop
    if V_CODE = V_CODE_TYPE_ENCAN then
    raise_application_error(-20050, 'Key duplicate');
    end if;

    end loop;

end TRG_PRIMARY_KEY_TYPE_ENCAN;

I am excepting my raise_application_error message to show in my php app to show that there's a 'Key duplicate'.

At the SQL level you can add constraints when you create the table. You probably won't need the PL/SQL trigger. Search for 'check constraint' e.g. at https://asktom.oracle.com/

Then in PHP, check the error return codes that the DB will return. See https://www.php.net/manual/en/function.oci-error.php e.g.

<?php
$stid = oci_parse($conn, "your SQL statement goes here");
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);  // For oci_execute errors pass the statement handle
    print htmlentities($e['message']);
    print "
<pre>
";
    print htmlentities($e['sqltext']);
    printf("
%".($e['offset']+1)."s", "^");
    print  "
</pre>
";
}
?>