Alphanumeric ID

queryfile.php
//function for creating an alphanumeric identification code
//(eg: 'FG00001').
include "functions.php";
//make the query to get the last ID from table
$results  = mysql_query('SELECT  id_record FROM table
                         ORDER BY  id_record  DESC LIMIT 1')
                or die (mysql_error());


if ($results) {
//combine the ID with a variable
  while ($result=mysql_fetch_array($results)) {
    $id_record = $result['id_record'];   
  }
  if (!$id_record) {
    $id_record = '';
    $id = cod_id('FG', $id_record);
  } else {
      $id = cod_id('FG', $id_record); 
  }
else {
    exit("Table does not exist.");
}


functions.php


function cod_id($cod, $id) {   
   $c = substr($id, -5, 5);
  
  //records from 2 to 99999.
  if (isset($id) && $id != '') { //verify a previous id     
    $n = $c + 1;        // if there is a previous id, add 1 to it


    //id numeric part
    if ($n >= 0 && $n <= 9) {
      $zero = '0000';
    }
    if ($n >= 10 && $n <= 99) {
      $zero = '000'; 
    }
    if ($n >= 100 && $n <= 999) {
      $zero = '00'; 
    }
    if ($n >= 1000 && $n <= 9999) {
      $zero = '0'; 
    }
    if ($n >= 10000 && $n <= 99999) {
      $zero = ''; 
    }   
  }
  //first record
  else {             //there is no id
    $zero = '0000';  //id numeric part
    $n = '1';        //first record
  } 
$id = $cod.$zero.$n;
return $id;
}

No comments:

Post a Comment