Liberator Liberator - 4 months ago 12
PHP Question

Adding PHP Echo 0000 prefix according to mysql ID number

I am building a POS with electronic invoices, because the invoice number will start with 1 and it is ugly to show invoice number : 1 I want to build something to add 00000 as prefix like this

$lastinvoice=mysqli_query($db, "SELECT * FROM `sales`
order by `id` DESC LIMIT 1");
$last_invoice=mysqli_fetch_assoc($lastinvoice);
$invoice=$last_invoice['id']+1;


building the prefix

$prefix=if (($invoice)<10){echo '0000000'};
elseif (($invoice)<100){echo '000000'};
elseif (($invoice)<1000){echo '00000'};
elseif (($invoice)<10000){echo '0000'};
elseif (($invoice)<100000){echo '000'};
elseif (($invoice)<1000000){echo '00'};
elseif (($invoice)<10000000){echo '0'};


Now in the HTML form I submit a hidden input like this

<input type="hidden" name="set_invoice"
value="<?php echo "$prefix$invoice"?>">


I am getting error with the builded prefix, it is not well made but because I am new to PHP I just do not know how to do that...

Any ideas ?

The error is

PARSE ERROR: SYNTAX ERROR, UNEXPECTED 'IF' (T_IF)
IN /HOME/LOCAL/PUBLIC_HTML/*******/SALES.PHP ON LINE 6


and Dreamweaver marks all the builded $prefix as bad coded

NOT A DUPLICATED

It is not a duplicated question. What I need is not only leading zeros but to check the last invoice and accoding to this apply the ammount of zeros and the links to the "duplicated" posted by someone does not solve the problem because is not the same kind of question ...

Answer

If you want your invoice number in 8, you can do like this:

 $invoice = sprintf("%08d", $invoice);

If $invoice is 12, it'll be 00000012

And for the next auto_increment:

 <?php
 $req = $bdd->query("SHOW TABLE STATUS FROM table_name LIKE 'table_name' ");
 $donnees = $req->fetch();
 echo $donnees['Auto_increment'];
 ?>