我有这个功能,但它不能100%工作,我不确定为什么。目前我加载了发票模板,它显示为0001。
如果我添加发票,它会被添加到数据库中,它的意思是如果最新的行不等于0001,那么将其设为0002,依此类推,如果它是1872则会进行下一次编号来自MySQL的最新发票。
PHP
define('INVOICE_INITIAL_VALUE','0001');
// Connect to the database
$mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
// output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT invoice FROM invoices ORDER BY invoice DESC LIMIT 1";
// mysqli select query
$result = $mysqli->query($query);
// get number of returned results, if 0 action it below
$row_cnt = $result->num_rows;
//Invoice length
$invoice = $row['invoice'];
if($row_cnt == "0"){
echo INVOICE_INITIAL_VALUE;
} else {
// check if the initial invoice ID has already been used and if not start from that value else from the next value
if($invoice != INVOICE_INITIAL_VALUE) {
echo ++$invoice;
}
}
// Frees the memory associated with a result
$result->free();
// close connection
$mysqli->close();
更新如下:
if ($result = $mysqli->query($query)) {
$row_cnt = $result->num_rows;
/* fetch object array */
while ($row = $result->fetch_row()) {
$invoice = $row['invoice'];
}
if($row_cnt == "0"){
echo INVOICE_INITIAL_VALUE;
} else {
// check if the initial invoice ID has already been used and if not start from that value else from the next value
if($invoice != INVOICE_INITIAL_VALUE) {
echo ++$invoice;
}
}
// Frees the memory associated with a result
$result->free();
// close connection
$mysqli->close();
}
答案 0 :(得分:0)
这样做的权利是将字符串转换为整数。然后用前导0转换回来。 如下例所示:
$num = '0001'; // string('0001')
$invoiceNumber = intval($num) + 1; // integer(2)
$invoice = str_pad($invoiceNumber, 4, '0', STR_PAD_LEFT); // string('0002')
因此您应该在代码中将其更改为:
else if($invoice != INVOICE_INITIAL_VALUE) {
$num = intval($invoice) + 1;
$invoice = str_pad($num, 4, '0', STR_PAD_LEFT);
echo $invoice;
}
虽然您应该将数据保存为整数,并将其显示为前导零。
答案 1 :(得分:0)
除了Dan Revah建议之外,你应该纠正你的if语句的逻辑。
if($invoice != INVOICE_INITIAL_VALUE) {
在上面一行中,您正在检查$ invoice是否不等于1,只有这样才能为其添加1。
因此,当$ invoice等于1时,您不会添加1.这就是您获得001的原因之一。