php 自动生成号码在新年开始时不起作用

xzlaal3s  于 2024-01-05  发布在  PHP
关注(0)|答案(1)|浏览(169)

我试图在php L5- 0124-0001中按以下顺序生成我的账单号(其中L5是公司名称,01代表月份,24代表年份,其中最后四位数字是序列号),我从2023年10月开始使用此代码,直到2023年底一切正常,但从今天开始2024年开始,它停止工作,(公司名称正确显示,年月也正确显示,但当需要生成新账单时,最后四位数字不增加。所有账单都保持为0001,而应该是L5-0124-0002等等........以下是代码

$CI = "L5"; //Example only
$CIcnt = strlen($CI);
$offset = $CIcnt + 6;

// Get the current month and year as two-digit strings 
$month = date("m"); // e.g. 09 
$year = date("y"); // e.g. 23  

// Get the last bill number from the database 
$query = "SELECT patientno FROM iap2 ORDER BY patientno DESC LIMIT 1"; 
$result = mysqli_query($con,$query); 
// Use mysqli_fetch_assoc() to get an associative array of the fetched row 
$row = mysqli_fetch_assoc($result); 
// Use $row[‘patientno’] to get the last bill number 
$lastid = $row['patientno'];     

// Check if the last bill number is empty or has a different month or year
if(empty($lastid) || (substr($lastid, $CIcnt + 1, 2) != $month) || (substr($lastid, $CIcnt + 3, 2) != $year)) { 
    // Start a new sequence with 0001 
    $number = "$CI-$month$year-0001"; 
} else { 
    // Increment the last four digits by one 
    $idd = substr($lastid, $offset); // e.g. 0001 
    
    $id = str_pad($idd + 1, 4, 0, STR_PAD_LEFT); // e.g. 0002 
    $number = "$CI-$month$year-$id"; 
}

字符串

flmtquvp

flmtquvp1#

你的代码有严重的缺陷。数字的构建方式,字母顺序和时间顺序是不一样的。所以当你获取“最后一个”数字时,你得到的是2023年12月的数字,而不是2024年1月的数字,因为1223(作为字符串)大于0124
您可以更改ORDER BY来修复它。但是这样查询将是未优化的(MySQL将需要扫描整个表),更重要的是,代码仍然存在缺陷,因为它对竞争条件很敏感。如果2个用户试图同时创建一个账单,他们最终可能会得到相同的数字。
生成号码的正确方法是使用专用的计数器表。当您需要获取新号码时:

  • 锁上table
  • 返回当前年份和月份的最后一次使用的计数器(以及公司,如果同一数据库中有多个)
  • 递增它并更新表
  • 把table摆好
  • 使用柜台插入新钞票

相关问题