我用 PHP 和 MySQL 开发了一个投标系统。 它在大多数情况下都运行良好,但我注意到当报价非常接近时会出现问题。
$now = DateTime::createFromFormat('U.u', microtime(true));
$dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");
$amountToRaise = 100;
$lastOffer = $bid->lastOffer();
//if there is an offer yet
if($lastOffer){
$newPrice = $lastOffer->getAmount()+$amountToRaise;
//else is the first offer
}else{
$newPrice = $amountToRaise;
}
//if the user is not the last bidder
if($user->getId() != $lastOffer->getUserId()){
$bidOffer = new BidOffer();
$bidOffer->setBidId($bid->getId());
$bidOffer->setUserId($user->getId());
$bidOffer->setAmount($newPrice);
$bidOffer->setTime($dateMicroTime);
$bidOffer->save();
//if this is not the first offer I give back the money to the previous user
if($lastOffer){
$lastUser = $lastOffer->user();
$lastUser->setCash($lastUser->getCash()+$lastOffer->getAmount());
$lastUser->save();
}
}
当报价在不同时刻完成,但用户在同一秒内报价时,代码效果很好,例如:18:00:01.1299022 和 18:00.02.1222377 之前拥有优惠的用户不会收到回优惠。 我怎样才能解决这个问题?我尝试使用临时变量来临时阻止语句,直到执行每个查询,但没有成功。
最佳答案
我会将 dateTime 与 microtime 分开,并且不会使用 $dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");
.
您可以使用微时间来提取最后的投标人。这可以通过在数据库中添加 bid_utime 列来完成。如果您按时间顺序查找一次拍卖的所有投标人 ORDER BY table.bid_utime DESC
。最后一个投标人可以通过 ORDER BY table.bid_utime DESC LIMIT 1
作为返回找到$lastOffer = $bid->lastOffer();
.
这也意味着您不会使用以下方式保存出价:$bidOffer->setTime($dateMicroTime);
而是使用以下方式保存:
$bidOffer->setDate($date);
和 $bidOffer->set_uTime($now);
但您也可以跳过所有这些,并使用 SELECT * FROM bid_Table ORDER BY ID DESC LIMIT 1
仅返回出价表中的最后一个条目,并忘记 dateMicroTime 和 microtime。希望这会有所帮助。
关于php - 如何用PHP正确管理竞价系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010548/