我正在为一个朋友写一页,人们可以预订课程。所有课程都有有限的插槽。当有两个请求时处理有限的课程插槽
在PHP页面上,我将获得课程的空闲插槽(从mysql),检查是否有足够的空间进行预订,然后将数据推送到mysql。
预订会保存在会话中,当用户填写信息并确认预订时,应执行此代码,验证并将所有这些代码保存到数据库中。
当同时有两个请求时会发生什么?我怎样才能保证免费插槽保持自由,直到我将数据推送到MySQL?
我会检查它这样
<?php
$canBook = true;
foreach ($_SESSION["booking"]->courseList as $booking) { //For all courses in the session
if ($booking->getCourse()->getFreeSlots() < $booking->slots) { //Check if there are enough slots
$canBook = false;
break; //Not enough free space. Cancel
}
}
if ($canBook) {
//Is the data still vaild? (Think about other requests)
$_SESSION["booking"]->save(); //Add booking to the database and reserve the slots
}
else
showError(); //Show the user an error
?>
难道这是一个问题,或者这是否永远不会发生?或者有更好的方法来解决这个问题吗?
谢谢
添
Tim,[this](https://stackoverflow.com/q/25335137/8469069)正是你需要解决这个问题。根据你的并发性,这可能是矫枉过正的,但你担心这一点很好。祝你好运! – ishegg