3

I want to make a id in database

id_user => data type 'varchar'

I want my id to start from 00, 01, 02, and so on. And to make new id, I count the all the rows, and the result from count will be added by 01.

Example:

$id=array(00,01,02);
$count_exist_id = $count($id)
$new_id= '00' + $count_exist_id

and I hope the new id must be '03' and it will be store to database in table user column id_user

Mureinik
  • 297,002
  • 52
  • 306
  • 350
nanasjr
  • 207
  • 1
  • 2
  • 12
  • 2
    Store `ID`s as number without `0` at the beginning, and than add zero at front/end, in your template. – pavel Jun 16 '15 at 05:57
  • How is `01` different from `1`? – knittl Jun 16 '15 at 06:06
  • ok i need for make id, it just make code for three, so i can make different between parents/root and childs/leave – nanasjr Jun 16 '15 at 17:14
  • linking parents and children together that way is a VERY bad idea if you ask me... that is not a normalized approach and will lead to further troubles for sure. If that relationship is important, it should be formalized through normalization... – Laurent S. Jun 18 '15 at 09:15
  • @Bartdude can you help me for another way to make linking parent and childrens, i really need it for make a tree like a family structure – nanasjr Jun 21 '15 at 17:12

2 Answers2

2

You can use INT(x) ZEROFILL, to add 0 before the number. '1' => '001'

With INT ZEROFILL, you have AUTO_INCREMENT. ;)

CREATE TABLE user (
   id_user INT(8) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT, 
   PRIMARY KEY(id_user)
);

If you use UNSIGNED, you optimize your table, and you save one BIT, to get bigger number.

See :

Community
  • 1
  • 1
user2226755
  • 12,494
  • 5
  • 50
  • 73
1

An easier approach would be to calculate the next id as an integer, and then pad it to a two character string:

$id = array(00,01,02);-
$count_exist_id = count($id);
$new_id = str_pad($count_exist_id, 2, '0', STR_PAD_LEFT);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • thanks for answer, i get it, and one problem again, i want make the child's from id, where `id_child = id_parent + 1 character` example : id_parent = (00) and id_child must be '001' || id_parent = (01) and id_child must be '010','011','012' – nanasjr Jun 16 '15 at 07:50