0

I have a primary key column, containing id so it must be unique

the content look like this

enter image description here

format of id is <index>/<division>/<month in roman>/<last 2 digit of year>

my question is what the best query to check if id already exist, and create id with <index>+1/<division>/<month in roman>/<last 2 digit of year>

this is my function to generate id

    public function gen_id($id_type = "HL.BY") {
    $id_num = 123;
    $month = $this->romanic_number(date("n"));
    $year = substr(date("Y"),-2);
    $index_number = sprintf("%04d", $id_num);

    $id = $index_number . "/" . $id_type . "/" . $month . "/" . $year;
    return $id;
}

if my question is not clear please ask

stacheldraht27
  • 392
  • 6
  • 23

1 Answers1

0

If you are required to use the existing database you can ensure unique ID's like this...

1) Create a table with two fields...

$createSQL1 = $conn->prepare("CREATE TABLE IF NOT EXISTS `nxtnum` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nxtnum` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

$createSQL1->execute();

$insertSQL1 = $conn->prepare("INSERT INTO `nxtnum` (`id`, `nxtnum`) VALUES (1, 501)");

$insertSQL1->execute();

Where "501" is the highest first-part of all existing ID's plus 1

2) Get the number for this line of your code... $id_num = 123; ...

$sql = "SELECT * FROM nxtnum";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);

where $conn is your database connection file

3) Create the new unique ID...

public function gen_id($id_type = "HL.BY") {
$id_num = $row['nxtnum']; // this is the new incremented number (incremented in step 4)
$month = $this->romanic_number(date("n"));
$year = substr(date("Y"),-2);
$index_number = sprintf("%04d", $id_num);

$id = $index_number . "/" . $id_type . "/" . $month . "/" . $year;
return $id;
}

4) Increment your counter...

$num = $row['nxtnum'] + 1;
$sql = "UPDATE nxtnum SET nxtnum=:num";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':num', $num, PDO::PARAM_INT);
$stmt->execute();

Now you're all set for the next ID and your ID's will always be unique

Happy Coding !

NOTE: Of course step one only has to be done once.

Kuya
  • 6,423
  • 4
  • 15
  • 31