如何使用PHP将字符串添加到随机生成的数字?

问题描述 投票:0回答:4

在我的PHP代码中,在插入新记录时,发票号应为0001.这里我想添加字符/单词(例如'optical'),它应该像optical0001。如何在号码前加上这个?

$query          = "select * from cust_report_invoices order by invoiceID desc limit 1";
    $result         = $link->query($query);
    $row            = $result->fetch_assoc();
    $invoiceNo      = $row['invoiceNo'];
    $prefix = 'Baopt_'; 
    $getinvoiceNo   = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);

$sql            = "INSERT INTO cust_report_invoices (invoiceNo,invoiceDate)
VALUES ('$getinvoiceNo', '$getinvoiceDate'            )";
php
4个回答
2
投票

str_pad返回字符串(doc)。所以只需与.结束:

$prefix = 'optical';
$invoice   = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT); 

编辑

添加新元素时需要删除前缀 - 您可以使用:

$prefix = 'Baopt_';
$invoiceNo = $row['invoiceNo']; 
if (substr($invoiceNo, 0, strlen($prefix)) == $prefix) // if already has prefix
    $invoiceNo = substr($invoiceNo, strlen($prefix)); // remove it
$getinvoiceNo   = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);

1
投票

在PHP中工作时,您可以使用.作为连接运算符。我看到你使用返回为字符串的函数str_pad

所以你可以像这样用发票号码连接前缀。

$prefix = 'optical';
$invoice   = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);

$prefix可以是你想要的任何东西。

invoice = 0001这个例子将返回optical0001


0
投票

只是"Opticals".$getinvoiceNo Dot连接字符串。


0
投票

不确定我是否理解正确,你想要将“光学”添加到$ getinvoiceNo?

如果是,则很简单,

invoiceId = "optical$getinvoiceNo"

© www.soinside.com 2019 - 2024. All rights reserved.