简体   繁体   English

多次更新数据库中的同一行

[英]Multiple update to the same row in database

I'm making a Billing system with some friends, it works this way: The customers make calls. 我正在与一些朋友建立一个计费系统,它的工作方式是:客户拨打电话。 The customers hangup the call. 客户挂断电话。 The price of the call is calculated. 计算通话价格。 The price of the call is reduced from the customer's credit. 通话价格从客户的信用中扣除。

We decided to make the following: Get the user's balance and store it in a variable, $balance, after do a $balance = $balance - $callprice, and finally update the database. 我们决定进行以下操作:获得用户的余额并将其存储在变量$ balance中,然后执行$ balance = $ balance-$ callprice,最后更新数据库。

The problem is that the customer can make simultaneous calls, and if two calls finish at the same time, and one of them gets the value on the database before the other script had updated the new balance... one of the calls will be lost. 问题是客户可以同时进行呼叫,并且如果两个呼叫同时完成,并且其中一个在另一个脚本更新新余额之前获得了数据库中的值,则其中一个呼叫将丢失。 I'm using php. 我正在使用php。

Any idea how can I do it? 知道我该怎么做吗?

Thanks, and sorry, I have a poor English... 谢谢,抱歉,我的英语不好。

The problem is it looks like you're trying to use two SQL statements to update the user's balance: One to SELECT the user's balance, then another to UPDATE the user's balance after the balance is subtracted using PHP. 问题是,您似乎正在尝试使用两个SQL语句更新用户的余额:一个SELECT用户的余额,然后另一个使用PHP减去余额后UPDATE用户的余额。

You could do it all in one operation and eliminate the possibility of race-conditions: 您可以一次完成所有操作,从而消除出现竞争状况的可能性:

UPDATE users
SET balance = balance - <callprice here>
WHERE user_id = <user_id here>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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