Umair Iftikhar
Umair Iftikhar

Reputation: 468

unique ids are not in sequence in PHP

I want to make a database primary key. I am using PHP uniqid() Function.

uniqid(php,true); 

Basically I want to add Student IDs in student table of database

e.g PHP-16-001

In which PHP is 3 character Course ID , 16 is year and 001 is student ID.

I can Add this via "."

$id = "php"."date('Y')".$i;

in which $i is a variable who is incrementing but when I fetch data from database I got

php16001

How can I got all characters?

Upvotes: 1

Views: 161

Answers (3)

Munjal Mayank
Munjal Mayank

Reputation: 131

A better way to do it:

if($i < 9)
{
    $i='00'.$i;
}

$unique_id = "PHP-".date('Y')."-".$i;

Upvotes: 1

eblin
eblin

Reputation: 446

Separate them by some character which you can then split by.

$id = sprintf("php-%s-%s", date('Y'), $i);

To "split" it back to individual chunks use explode

$idParts = explode("-", $string);

Upvotes: 1

Karthik N
Karthik N

Reputation: 951

String concatenation operator in php is '.', so to get your extra '-' characters add them to you string, Check the below code. You should insert your unique id in database as "php-16-001". Make sure your $i variable is a string.

$id = "php-" . date('y-') . $i;

Upvotes: 1

Related Questions