我需要从一个表的整数生成发票编号,该表具有用户购买保存的数据库的自动递增ID。
表invoice数据库的示例:
发票编号格式下限采用以下两种方式之一。
示例1:不带前缀的发票数量:
0000001 | 0000002 | 0000003 | 0000004 | 0000005
示例2:带有前缀的发票数量:
F-0000001 | F-0000002 | F-0000003 | F-0000004 | F-0000005
问题:
PHP 1)?您可以直接从MySQL或执行此操作的最佳方法是什么?
2)?示例1或示例2最合适的格式是什么?
感谢您一如既往的支持!
发布于 2015-11-09 12:30:57
多亏了Gordon Linoff,我才有办法解决这个问题。
我将分享一个例子,也许有人会感兴趣。
SQL -不带前缀的发票: SELECT id, LPAD(id,7,'0') FROM invoice WHERE id = 1;
结果: 0000001
SQL -带有前缀的发票: SELECT id, CONCAT( 'F-', LPAD(id,7,'0') ) FROM invoice;
结果: F-0000001
发布于 2018-06-30 06:48:42
您可以在PHP中编写一个很好的助手函数,以便在应用程序中的任何需要返回发票号的地方使用它。下面的helper函数可以简化您的过程。
function invoice_num ($input, $pad_len = 7, $prefix = null) {
if ($pad_len <= strlen($input))
trigger_error('<strong>$pad_len</strong> cannot be less than or equal to the length of <strong>$input</strong> to generate invoice number', E_USER_ERROR);
if (is_string($prefix))
return sprintf("%s%s", $prefix, str_pad($input, $pad_len, "0", STR_PAD_LEFT));
return str_pad($input, $pad_len, "0", STR_PAD_LEFT);
}
// Returns input with 7 zeros padded on the left
echo invoice_num(1); // Output: 0000001
// Returns input with 10 zeros padded
echo invoice_num(1, 10); // Output: 0000000001
// Returns input with prefixed F- along with 7 zeros padded
echo invoice_num(1, 7, "F-"); // Output: F-0000001
// Returns input with prefixed F- along with 10 zeros padded
echo invoice_num(1, 10, "F-"); // Output: F-0000000001
一旦完成了帮助函数的编写,就不需要每次在查询中使用LPAD
或CONCAT
MySQL函数来返回带有填充零或带前缀的零的ID。如果您对整个应用程序中的helper函数具有全局访问权限,则只需在想要生成发票编号的地方调用它。
发布于 2015-11-09 12:29:55
1 - 0000001 | 0000002 | 0000003 | 0000004 | 0000005
$dbValue = 1;echo $dbValue = str_pad($dbValue,7,"0",STR_PAD_LEFT);//会给出0000001;
2 - F-0000001 | F-0000002 | F-0000003 | F-0000004 | F-0000005
$dbValue = 1;echo $dbValue = "F-".str_pad($dbValue,7,"0",STR_PAD_LEFT);//会产生F-0000001;
https://stackoverflow.com/questions/33602376
复制相似问题