0

I have stored some numaric data with varchar datatype in database, something like ( 00005 ) as studentid

After retrieving it from database, i want to auto increment it by 1 like below:

echo $data['studentid']+1; ---> but the result will be only 6, the zero's are removed, because it being changed from string to integer.

My Question is that: Is there any possiblity that the result would be like 00006 not only 6?

Please help me regarding the issue and advise me about my mistakes and suggest me for better ways to do it.

  • is the length of the string fixed, or there could be a string like 0005 and one other like 00000003 ? – fthiella Nov 09 '13 at 17:01
  • The answer to your question is correctly given below. However, if the student id is a number I am curious why you would store it as a varchar in your database. You better have a very good reason not to use an integer type :-) – CompuChip Nov 09 '13 at 17:02
  • i have stored as **varchar** because the **int** datatype does not leading zeros – Mohammad Samim Samimee Nov 10 '13 at 05:17
  • Like @CompuChip says, it would be better to store it as an `int` (this is neater and allows sorting etc.) and then use my answer whenever you either display it or increment it. – Tum Nov 12 '13 at 21:38

1 Answers1

1

Use this:

echo sprintf("%06s", $data['studentid']+1);
Tum
  • 6,937
  • 2
  • 25
  • 23
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 07:39