简体   繁体   中英

Prevent Select sql from select the same data from DB PHP

I Have some question about the Seq in PHP. I create 1 tabel to maintain the sequence table, ex. table is sequence and the field is seq(start from 1) The sequence should be unique value.

The problem is. there is 2 process which is run parallel that will use it. and I got the error message that say duplicate value.

The question. How to lock the table from another select query?

this is my code

//select seq
$sqlSeq = "select seq from sequence for update";
$resultSeq = pg_query($sqlSeq);
$rowSeq = pg_fetch_assoc($resultSeq);
$seqCif = $rowSeq['seq'];

//INSERT
$sqlInsert1 ="insert into TEST (customer_id) values( '".$seqCif."')";

//UPDATE 
 $sqlInsert1 .= "update sequence set seq=seq+1;" ; 

Can you help me for this case? Many Thanks befor..

One simple way to make the operation atomic and to guarantee an incremental id without gaps is to turn the statement to an insert... select... query:

insert into test(customer_id)
select coalesce(max(customer_id), 0) + 1 from test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM