Skip to main content

Generating serial number in PHP/MySQL

As a programmer we sometimes need to generate some sort of serial number.

I found this code when I was developing a project for my ex-employer.
<?php

$id = 1;
if($id <= 9){
 $key = '000000' . $id;
} elseif ($id > 9 && $id <= 99) {
 $key = '00000' . $id;
} elseif ($id > 99 && $id <= 999) {
 $key = '0000' . $id;
} elseif ($id > 999 && $id <= 9999) {
 $key = '000 '. $id;
} elseif ($id > 9999 && $id <= 99999) {
 $key = '000' . $id;
} elseif ($id > 99999 && $id <= 999999) {
 $key = '000' . $id;
} else {
 $key = $id;
}
echo $key;

By using the str_pad function, we can simplify above code to:
<?= str_pad($id, 7, '0', STR_PAD_LEFT); ?>

It can also be written entirely in MySQL.
SELECT LPAD(id, 7, 0) AS serialNo from tableName;

Comments

Popular posts from this blog