0

Hey guys, I want to generate a unique number in PHP (ex. 000001, 000002 etc), when it is saved in the database it will increment in 1 (+1). But how can I do it? Thank You :)

5
Contributors
5
Replies
45
Views
3 Years
Discussion Span
Last Post by bLuEmEzzy
1

If you want something like you showed in the example. str_pad() will help you.

  //Assuming $id is the AUTO_INCREMENT id from the database
  $unique_number = str_pad($id, 5, "0", STR_PAD_LEFT); 
3

If you set your DB table's primary key to auto increment, you aren't going to be able to set a fixed length of numbers and pad them to the left with zeros. If you want to display it in that format (00000001 vs 1) then you'll have to handle that in your application.

1

Second that. I'd use normal autoincrement to store integers and provide LPAD in your SELECT queries OR use php's str_pad when you retrieve the data. Don't make the DB work too hard ;)

0

@JorgeM, I do not use auto increment on my field. Thank you for all the suggestions. I'll get back for improvements. Cheers!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.