php - MySQL 如何同时管理来自多个用户的多个查询?

标签 php sql mysql

举个例子:

我有一个管理用户投票的 PHP 脚本。

当用户投票时,脚本会查询以检查是否有人已经为相同的 ID/产品投票。如果没有人投票,那么它会进行另一个查询并将 ID 插入到通用 ID 投票表中,然后再进行一次查询以将数据插入到每个用户 ID 投票表中。这种行为在其他类型的脚本中重复出现。

问题是,如果两个不同的用户同时投票,代码的两个实例可能会尝试插入一个新的 ID(或某种类似类型的查询),这会产生错误??

如果是,我如何防止这种情况发生?

谢谢?

重要提示:我正在使用 MyISAM!我的虚拟主机不允许 InnoDB。

最佳答案

The question is, if two different users votes simultaneously its possible that the two instances of the code try to insert a new ID (or some similar type of query) that will give an erro

是的,您最终可能会通过两个查询执行插入。根据表的约束,其中之一会产生错误,或者您最终会在数据库中有两行。

我相信你可以通过应用一些锁定来解决这个问题; 例如如果需要给id为theProductId的产品投票:(伪代码)

START TRANSACTION;
//lock on the row for our product id (assumes the product really exists)
select 1 from products where id=theProductId for update;
//assume the vote exist, and increment the no.of votes
update votes set numberOfVotes = numberOfVotes + 1 where productId=theProductId ;
//if the last update didn't affect any rows, the row didn't exist
if(rowsAffected == 0) 
  insert into votes(numberOfVotes,productId) values(1,theProductId )
//insert the new vote in the per user votes
insert into user_votes(productId,userId) values(theProductId,theUserId);
COMMIT;

更多信息 here

MySQL 还提供了另一种解决方案,可能适用于此,insert on duplicate

例如你也许可以这样做:

 insert into votes(numberOfVotes,productId) values(1,theProductId ) on duplicate key 
   update numberOfVotes = numberOfVotes  + 1;

如果您的投票表在产品 ID 列上有一个唯一键,上面将 如果特定的 theProductId 不存在,则执行插入,否则它将执行更新,其中它将 numberOfVotes 列递增 1

如果在将产品添加到数据库的同时在投票表中创建一行,则可能会避免很多这样的情况。这样您就可以确定您的产品始终有一行,并且只需对该行发出更新。

关于php - MySQL 如何同时管理来自多个用户的多个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851767/

相关文章:

php - 如何根据 PHP 中的键名删除数组项?

php - 无法显示来自 MySQL 的图像

javascript - 根据条件改变列表元素的颜色

sql - 解析 XML 以构建动态查询

sql - 多行列值转换为单行

php - 使用 php 将图像保存到不同的 url

mysql - RDS到本地DB恢复错误

mysql - 查找特定日期范围内每个商店每个销售人员售出的商品总数

php - 为什么DBF在PHP中会显示为不良记录,而在直接查看时却不会显示为不良记录?

python - 使用原始 SQL 且无参数执行安全 SQL SELECT 语句