最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

options - get_option() and update_option() in a transaction (for an autoincrement value)

programmeradmin2浏览0评论

I need an autoincremented ID for a custom post type to manage order IDs. For this, I would use the WP Options API, but I'm afraid of a typical transaction issue:

$count = get_option('my_id');
update_option('my_id', $count + 1);

When there is running a parallel request, $count could be the same value in both requests.

So: Is it somehow possible to set this code part as a transaction to prevent this issue?

Edit: Example scenario for a failed autoincrement: If two users hit at the exact time time the process, where the code above will be executed, this may happen:

user 1: $count = get_option('my_id') // $count = 1
user 2: $count = get_option('my_id') // $count = 1
user 1: update_option('my_id', $count + 1); // 'my_id' = 2
user 2: update_option('my_id', $count + 1); // 'my_id' = 2

In a transaction, the database would wait for user 1 to get and update the value for 'my_id'. When user 1 finished the transaction process, user 2 would get the correct updated value.

发布评论

评论列表(0)

  1. 暂无评论