title: PHP - generate serial number
body: <p>Can someone tell me if there's a better way doing this?</p>
  
  <ul>
  <li>I am trying to generate a Serial number (function Taken from a Post on
  this site ) </li>
  <li>Check in my database if this Serial exist, if it does,regenerate another </li>
  <li><p>Insert Unique serial into Db</p>
  
  <pre><code>function GenerateSerial() {
  $chars = array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
  $sn = '';
  $max = count($chars)-1;
  for($i=0;$i&lt;20;$i++){
   $sn .= (!($i % 5) &amp;&amp; $i ? '-' : '').$chars[rand(0, $max)];
    }
  return $sn;
   }
  
  
   // Generate SN
  $serial =  GenerateSerial() ;
  
  
  // Check if it exists, then re-generate
  
   function checkifSerialexist () {
  
   $statement = $dbh-&gt;prepare("SELECT `id` FROM `table` WHERE `SN` = :existSN");
   $statement-&gt;bindParam(':existSN',  $serial, PDO::PARAM_STR); 
   $statement-&gt;execute();
   $statement-&gt;setFetchMode(PDO::FETCH_ASSOC);
   $result = $statement-&gt;fetchAll();
   $serial_count = $statement-&gt;rowCount();
  
   if ($serial_count &gt; 0) {
  
   $serial =  GenerateSerial() ;
  
  } 
  
  
   return $serial ;   
  
  }
  
  
  //Now insert unique SN
  
  $stmt = $dbh-&gt;prepare("INSERT INTO `table` (SN) VALUES (:sn)");
  
  $stmt-&gt;bindParam(':sn', $serial, PDO::PARAM_STR);
  
  ect....
  </code></pre></li>
  </ul>