0

In my php code, while inserting new record, invoice number should be 0001. Here I want to add characters/a word(for example 'optical') and it should be like optical0001. How can I add this before the number?

$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'            )";
1

4 Answers 4

2

str_pad return string (doc). So just concat with .:

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

Edit

When adding new element you need to cut the prefix out - you can use this:

$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);
Sign up to request clarification or add additional context in comments.

8 Comments

invoiceno is unique key in database.Here am facing issue ie when first time am inserting like Baopt_001.It is not adding Baopt_002 on the second time.Its still adding Baopt_001 on the second insertion and so it is showing error called duplicate entry
@becool What is the code you use to insert data to DB? this seem new issue and not related to the string concatenation - Did you open new question about it?
there is no issues in insert query.In this code invoice number is not adding thats my issue
Does "invoiceNo" field in the DB is int or string?
when i removed "Baopt_ ".it will insert like 001 ,002 etc...I am facing issue when "Baopt_ "added
|
1

When working in PHP you can use the . as concatenation-operator. I see that you use the function str_pad that returns as string.

So you can just concat the prefix with the invoice number like this.

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

$prefix can be anything you want.

When invoice = 0001 this example will return optical0001

Comments

0

Just "Opticals".$getinvoiceNo Dot is concatenating strings.

Comments

0

Not sure if I understand correctly, you want to prepend "optical" to $getinvoiceNo?

If yes then it is simple,

invoiceId = "optical$getinvoiceNo"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.