php - 如何用PHP正确管理竞价系统?

标签 php mysql

我用 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/

相关文章:

php - 为什么“print”和 "echo"函数不需要括号

javascript - 我的 Ajax 调用。总是返回错误

mysql - 在 Group By 中使用 CASE 语句查询 我需要创建一个条目,其中 WHEN 中没有结果

java - 当存在@Embeddable ID时如何正确插入@Entity

php - 此后如何使用 explode ,因为在我的数据库列中,所有值都在产品列中可用,如下所示

php检测/获取发布请求的发件人url(或服务器)

php - jQuery 悬停效果 iPhone/iPod touch/iPad 不起作用

php - 在 laravel blade Laravel 5.5 中找到许多列的总值

mysql - 这在mysql中可能吗?

mysql - 运行 mySQL 语句不会返回任何结果