PHP Oracle事务插入错误

时间:2014-05-08 12:58:31

标签: php sql oracle

我浪费了足够的时间,我需要你的帮助。它可能是一个简单的疏忽,但我使用此函数连接到oracle数据库并执行事务:

function transaction($query, $loop, $read_only, $return_vals){
     $DEBUG = 'yes';

    $db_name_idde = "server";
    $db_user_idde = "schema";
    $db_pass_idde = "password";

    $connection = oci_new_connect($db_user_idde, $db_pass_idde, $db_name_idde);

    $return_vars = array();

    //foreach always needs an array
    if( gettype($query) == 'string'){
        $query = array(0 => $query);
    }

    foreach($query as $statement){

        $stid = oci_parse($connection, $statement);

        if (!$stid && $DEBUG == "yes") {
            die(oci_error($connection));
        } else if (!$stid) {
            die('Could Not Execute Query.');
        }


        if ( !oci_execute($stid, OCI_DEFAULT) && $DEBUG == "yes") {

        // If we have a problem, rollback then die
            oci_rollback($connection);
            oci_close($connection);

            die($statement);
            //die(oci_error($stid));
        } else if ( !oci_execute($stid, OCI_DEFAULT) ) {
            oci_rollback($connection);
            oci_close($connection);

            die('Could Not Execute Query.');
        }
    }

    oci_commit($connection);
    oci_close($connection);

    // See if we need to send the results back
    if ($return_vals) {
        if ($loop) {
            $i = 0;
            while ($row = oci_fetch_array($stid, (OCI_RETURN_NULLS+OCI_ASSOC))) {
                $return_vars[$i] = $row;

                $i ++;
            }
        } else {
            $return_vars = oci_fetch_array($stid, (OCI_RETURN_NULLS+OCI_ASSOC));
        }
    } else {
        //$return_vars = mysql_insert_id($connection);
    }

    global $db_num_results;
    global $zero;
    $db_num_results = $i;
    $zero = 0;

    return $return_vars;
}

现在这个函数可以处理更新但总是失败,插入,INSERT INTO或INSERT ALL,声明随机生成的OBJECTID的重复键。我开始使用mt_rand,它生成的ID比DB中的任何内容长得多,所以它根本不应该声明:

INSERT ALL

INTO table1 (OBJECTID, OUTFALL_ID, INVESTIGATION_ID, LOGGED_DATE,LOGGED_BY,ASSET_ID,SOURCE,COMMENTS,STATUS, CREATED_BY, CREATED_DATE) 
VALUES ( 1314897731, '10C10010', TO_CHAR(SYSDATE, 'YYYY') || '-' || sequence.NEXTVAL,  TO_DATE('05/15/2014','mm/dd/yyyy'),'person','','Sample','','Open', 'a@b.com', SYSDATE)

INTO table2 (OBJECTID, OUTFALL_ID, INVESTIGATION_ID, TASK_DATE,TASK_TIME,ENTERED_BY,TASK_TYPE,DOCUMENT_LINK,SUMMARY, CREATED_BY, CREATED_DATE) 
VALUES ( 1314897731, '10C10010', TO_CHAR(SYSDATE, 'YYYY') || '-' || sequence.CURRVAL,  TO_DATE('05/24/2014','mm/dd/yyyy'),'','person','Initial Inspection','','', 'a@b.com', SYSDATE) SELECT * FROM DUAL 

然而,当我在TOAD中运行此声明时,没有任何投诉,并且不应该考虑我生成的新ID至少是目前在那里的ID的10倍。也许我在那里留下了一些PL / SQL,或者它意外地重复了一遍。我不知道。

1 个答案:

答案 0 :(得分:0)

罪魁祸首是:

!oci_execute($stid, OCI_DEFAULT)

由于某种原因,这会强制出现唯一约束错误,这种错误在异常情况下会返回true / false并且可以在if语句的条件中使用。将其更改为

$r = oci_execute($stid, OCI_DEFAULT);
if(!$r && $DEBUG == 'YES'){

删除了错误。这并不能解释为什么更新正常工作,但自从我实施此更改以来,我没有遇到任何麻烦。