0

I just wanted to create sequential ID with suffix and prefix in php. I have done some of the parts but, i need to do that if the id existed in DB variable $i shall be incremented by one to generate the next sequential unique id. I have done this but the ID didn't increment after 2. So any help will be appreciated.

Thank you!

this is the code that check the id exist in the db and generate next unique id number.

for($i = 1 ; $i <= 1000; $i++) {

        $formnum = sprintf('%04d', $i);
       $id2 = "Prefix".$formnum.date("Y");
        $q = "SELECT * FROM table where id='$id2'";
       $chk = new DBConnection();
      $opchk = $chk->executeQuery($q);

      $fetres = mysql_num_rows($opchk);
      if( $fetres >0){

          $i = $i + 1;
          do {
              $formnum = sprintf('%04d', $i);
              return $formnum ;
          }while ($i<=1000);

        }else{
      return $formnum ;

    }
}
Fekade
  • 17
  • 1
  • 4
  • 1
    Why are you trying to generate your own unique id. Use AUTOINCREMENT instead and it is all done by MYSQL – RiggsFolly Jul 03 '17 at 11:57
  • Even if the above code did work, it would be really inefficient. Imagine, if you already have 999 records for a given prefix, your code would issue 1000 selects to determine the next possible value. But this question has been asked multiple times already here on SO. – Shadow Jul 03 '17 at 13:15

0 Answers0