我有这个功能,但它不能 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 将其转换回来。 就像下面的例子:
$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;
}
尽管您应该将数据保存为整数并仅以前导零表示。
关于php - 使用 PHP 增加 MySQL 数据库的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30100242/