如何解决具有唯一ID PHP,ORACLE 12C的问题

问题描述 投票:0回答:1

使用PHP + Oracle 12c

我正在尝试插入许多行,但出现错误"oci_execute(): ORA-00001: unique constraint (S95417.FIRMA__IDX)",这对我来说很奇怪,因为在循环中我获取了最后一个id并将其递增。

我使用了debbuger,并且(在插入时)我得到了最后一个ID,但是递增不起作用。你能告诉我为什么吗?

我添加的数据

INSERT INTO FIRMA VALUES(18,MICROSOFT,2432213715,2020-03-26,23)
INSERT INTO FIRMA VALUES(19,APPLE,7512202082,2020-03-26,42)





SELECT NVL(MAX(firmaid),0)+1

我使用其他表使代码非常相似,并且工作正常。

我的代码:

  $ile_razy = $_POST['liczba_powtorzen'];

    $firma = "SELECT * FROM FIRMA";

    $c = oci_connect($username, $password, $database);
    if (!$c) {
        $m = oci_error();
        trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
    }

        $file = 'firma.txt';
        $current = file_get_contents($file);

    for ($i = 1; $i <= $ile_razy; $i++) {

        $nazwa = randCompanyName();
        $nip = randNIP();
        $dataWspolpracy = date("Y-m-d");

        $ids_array = array();

        $adresid = "SELECT adresid FROM ADRES";

        $stmtt = oci_parse($c, $adresid);

        $result = oci_execute($stmtt);

        while($row = oci_fetch_array($stmtt))
        {
            $ids_array[] = $row['ADRESID'];
        }
        $randIndex = array_rand($ids_array);
        $adresId = $ids_array[$randIndex];

    // HERE IS PROBLEM
        $firmaQuery = "INSERT INTO FIRMA SELECT NVL(MAX(firmaid),0) + 1,'$nazwa', '$nip', '$dataWspolpracy', '$adresId' from FIRMA";
        $ex = oci_parse($c,$firmaQuery);
// "zapytanie" is working fine
        $zapytanie = "SELECT NVL(MAX(firmaid),0)+1 from FIRMA";
        $stmt = oci_parse($c, $zapytanie);
        $results = oci_execute($stmt);
        while($row = oci_fetch_assoc($stmt)){
            $rowid  = $row["NVL(MAX(FIRMAID),0)+1"];  
        }
        $firmaIdForTxt = "INSERT INTO FIRMA VALUES(".$rowid.",".$nazwa.",".$nip.",".$dataWspolpracy.",".$adresId.")";
        echo $rowid. ", ";
        oci_execute($ex);
        $current .= $i. ".".$firmaIdForTxt."\n";
        file_put_contents($file, $current);
        }

enter image description here

在我的数据库中enter image description here

我已经更改了,但仍然出现错误

enter image description here

php oracle oci
1个回答
0
投票

您可以将FIRMAID设置为identity column:Oracle会在内部处理增量,这对于您的数据更安全。

然后您可以通过此查询插入数据:

INSERT INTO FIRMA(nazwa, nip, datawspolpracy, adresid) VALUES('$nazwa', '$nip', '$dataWspolpracy', '$adresId')

[注意:这是一个快速答案,为了更安全的解决方案并避免SQL注入,请使用准备好的语句:PHP oci examples(请参见示例2)

© www.soinside.com 2019 - 2024. All rights reserved.