ecshop 秒杀并发时库存会被减到小于0的解决办法
ecshop 秒杀并发时库存会被减到小于0更新库存后,再进行库存检查,如果库存为负数,则执行事务的回滚。
begin();//开始一个事物处理开始 $sql = "UPDATE ".$GLOBALS['a']->table('seconds_kill')." SET kill_stock = kill_stock - 1 WHERE sk_id='".$sk_id."' LIMIT 1" ; $GLOBALS['db']->query($sql); $sql = "SELECT kill_stock ". " FROM ".$GLOBALS['a']->table('seconds_kill'). " WHERE sk_id='".$sk_id."'"; $kucun = $GLOBALS['db']->getOne($sql); if($kucun<0){ rollback(); show_message('很抱歉,您购买的商品库存不足! ', '返回', '', 'error'); die(); }else{ commit(); } //开始 function begin(){ $GLOBALS['db'] -> query("set autocommit=0");//设置自动提交 $GLOBALS['db'] -> query("begin");//事务开始 } //提交 function commit(){ $GLOBALS['db'] -> query("commit");//提交 $GLOBALS['db'] -> query("set autocommit=1"); } //回滚 function rollback(){ $GLOBALS['db'] -> query("rollback");//回滚所做的数据库更改 $GLOBALS['db'] -> query("set autocommit=1"); }