Would this WPDB setup result in potential race conditions?

I have a page on my site with numerous elements that can be likeddisliked through a simple admin-ajax call.In the assoc

I have a page on my site with numerous elements that can be liked/disliked through a simple admin-ajax call.

In the associated PHP code, it looks like this:

// Fetch the existing meta from this element. The array of users who already voted, and the current score.
global $wpdb;
$row = $wpdb->get_row( "SELECT `rating_users`, `rating_score` FROM `table` WHERE `file_id` = $file_id" );

$voted_users   = $row->rating_users? unserialize( $row->rating_users) : array();
$current_score = $row->rating_score ?: 0;

// Now verify this current user has not already voted, check the array.
foreach ($voted_users as $id => $ip)
{
    // check if current user ID / IP has voted, exit if true...
}

// Good to go, add this user to the list of users who have voted now.
$voted_users[] = array(
    $user_id => $user_ip
);
$current_score++;

$wpdb->update(
    'table',
    array(
        'rating_users' => serialize( $voted_users ),
        'rating_score ' => $current_score
    ),
    array(
        'file_id' => $file_id
    ),
    array( '%s', '%d' ),
    array( '%d' )
);

So I feel like in between the time I (retrieve the current list of users who have voted / score...verify if this is a valid vote...and then adjust/update the values back into the database) another user could have initiated the same process - and thus are dealing with "wrong" data. Data would be lost as one process would override the other's upon the wpdb->update call.

I haven't verified this, as emulating a race condition is difficult, but seems valid - what is a better method of performing the above that wouldn't result in this issue?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744614749a4583982.html

相关推荐

  • Would this WPDB setup result in potential race conditions?

    I have a page on my site with numerous elements that can be likeddisliked through a simple admin-ajax call.In the assoc

    2天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信