문제

I need to create an invoice number in format:

CONSTANT_STRING/%d/mm/yyyy

mm - Month (two digits) yyyy - Year

Now, the %d is the number of the invoice in the specific month. Another words, this number is reseted every month.

Now I am checking in database what is the highest number in current month. Then after its incrementation I am saving the row.

I need the whole number to be unique. However, it sometimes happens that it is being duplicated (two users save in the same time).

Any suggestions?

도움이 되었습니까?

해결책

Put a unique index on the field and catch the database error when trying to save the second instance. Also, defer getting the value until the last possible moment.

다른 팁

One solution is SELECT ... FOR UPDATE, which blocks the row until you update it, but can cause deadlocks with a serios multitasking application.

The best way is to fetch the number and increment it in a transaction and then start the work. This way, the row is not locked for long.

Look into BEGIN WORK and COMMIT.

Use the primary key (preferably an INT) of the invoice table or assign a unique number to each invoice, e.g. via uniqid.

PS. If you are using uniqid, you can increase the uniqueness by setting more_entropy parameter to true.

set the id all in one query.

$query = 'INSERT INTO table (invoice_number) VALUES (CONCAT(\''.CONSTANT.'\', \'/\', (SELECT COUNT(*) + 1 AS current_id FROM table WHERE MONTH(entry_date) = \''.date('n').'\' AND YEAR(entry_date) = \''.date('Y').'\'), \'/\', \''.date('m/Y').'\'))';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top