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 :)

Recommended Answers

All 5 Replies

In your database if you use AUTO_INCREMENT, see here.

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); 

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.

Member Avatar

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 ;)

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.