【问题标题】:Raise Application Error when user enters duplicate primary key in PHP app from Oracle当用户从 Oracle 在 PHP 应用程序中输入重复的主键时引发应用程序错误
【发布时间】:2019-11-25 16:57:54
【问题描述】:

我不确定从哪里开始在我的 php 应用程序中从 oracle 引发错误。每当用户(这里是我们)输入重复的主键、外键违规甚至不是空值时,我都需要引发错误。问题是,我不确定从哪里开始,我需要在这里使用触发器吗?

看看下面的代码,我想我快到了,但我不知道从现在开始该做什么。这只是我的主键错误的代码。当然,我假设如果我可以使这个工作正常,那么其他错误应该不会太难编码

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;

我在我的 php 应用程序中显示的 raise_application_error 消息除外,以表明存在“密钥重复”。

【问题讨论】:

    标签: php oracle stored-procedures triggers procedure


    【解决方案1】:

    在 SQL 级别,您可以在创建表时添加约束。您可能不需要 PL/SQL 触发器。搜索“检查约束”,例如在https://asktom.oracle.com/

    然后在 PHP 中,检查 DB 将返回的错误返回代码。参见https://www.php.net/manual/en/function.oci-error.php 例如

    <?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 "\n<pre>\n";
        print htmlentities($e['sqltext']);
        printf("\n%".($e['offset']+1)."s", "^");
        print  "\n</pre>\n";
    }
    ?>
    

    【讨论】:

    • 你能在检查约束中添加 raise_application_error 吗?
    猜你喜欢
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2015-02-10
    相关资源
    最近更新 更多