I'm encountering a problem with the generation of a number which increases everytime an operation is called.
When the value arrive to 10, i can't print 11 and so on...
$this->sql = "SELECT codice FROM accettazione ORDER BY id DESC LIMIT 1";
if ($result = $this->hookUp->query($this->sql)) {
if ($result->num_rows > 0) {
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = substr($rw['codice'], -1);
if ($codice < 9) {
$rw['codice'] = date("Y") . ".0000";
} else /*if ($codice == 9 || $codice < 99)*/ {
$rw['codice'] = date("Y") . ".000";
}
echo $rw['codice'] . ++$codice;
}
} else {
echo date("Y") . ".00001";
}
} else if ($this->hookUp->query($this->sql) === false) {
echo "fail";
}
}
The goal is to print 00001 when the value is lower than 10, ++00010 when lower than 100, ++00100 when lower than 1000, and so on...
When the code is 00010, at 00011, the value goes back to 00001 (if ($result->num_rows > 0) isn't satisfied anymore).
In the mySQL table, $rw["codice"] is a VARCHAR.
Why?
I guess you want your values displayed with leading zeros. That is:
1 displayed as 00001
9 displayed as 00009
11 displayed as 00011
1234 displayed as 01234
This is a requirement as old as the IBM 029 keypunch machine. (If I guess incorrectly, please edit your question.)
It's easy in php using sprintf.
$string_codice = sprintf('%05d', $codice);
EDIT
I think you're doing this the hard way. It looks like you want a string that reads 2015.00001 or 2015.09876 or suchlike. But I'm not confident guessing your requirements from your code. For one thing, I don't know what the values in your codice column in your database table look like.
Maybe you could try something like this.
/* assume the counter starts at zero */
$codice = 0;
if ($result->num_rows > 0) {
/* fetch the counter value from the table if nay. */
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = $rw['codice']; /* no substr */
}
}
/* add one to the value and format it YYYY.000nn */
$codice++;
$stringval = date("Y") . "." . sprintf('%05d', $codice);
echo $stringval;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With