PHP和MySQL - 从数据库中的整数生成发票编号

Lea*_*ing 8 php mysql invoice

我需要从表的整数生成一个发票号,其中包含用户购买保存的数据库的自动递增ID.

表发票数据库的示例:

在此输入图像描述

发票号码格式的地板有两种方式.

示例1:没有前缀的发票数量:

0000001 | 0000002 | 0000003 | 0000004 | 0000005

示例2:带前缀的发票数量:

F-0000001 | F-0000002 | F-0000003 | F-0000004 | F-0000005

题:

1)¿最好的方法是什么,你可以直接从MySQL或PHP做?

2)¿什么是最合适的格式示例1或示例2?

我一如既往地感谢您的支持!

Lea*_*ing 10

感谢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


Wol*_*ine 7

您可以在PHP中编写一个好助手函数,以便在应用程序中希望返回发票编号的任何地方使用它。以下帮助程序功能可以简化您的过程。

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
Run Code Online (Sandbox Code Playgroud)

编写完辅助函数后,无需在查询中每次使用LPADCONCATMySQL函数来返回带填充零或带前缀零的ID。如果您可以在整个应用程序中全局访问帮助程序功能,则只需在要生成发票编号的任何地方调用它即可。


LOK*_*ESH 5

从数据库中获取最后一个ID,并将其存储在PHP变量中。

例如,如果最后一条记录是100,则将其增加1

$last = 100; // This is fetched from database
$last++;
$invoice_number = sprintf('%07d', $last);
Run Code Online (Sandbox Code Playgroud)

最后,第二个问题的答案是

$number = "F-". $number;
Run Code Online (Sandbox Code Playgroud)


小智 5

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;