title: Generate a Unique ID using PHP and MYSQL
body: <p>Hi I am creating a system that processes and ID and a UID, The UID we are generating randomly but I am a little stuck, I need to always generate a UID that does not currently exist in the db as the field is a unique field used on the front end so as not to expose the real ID.</p>
  
  <p>So to recap, I am trying to generate a unique id that does not currently exist in the DB the part I haven't got working is the cross checking in the db so it sometimes will give a number that already exists in the db even though it shouldn't thanks in advance.</p>
  
  <p>This is my code so far:</p>
  
  <pre><code>function uniqueID($table) 
  {
  $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
  
  $possible = '1234567890';
  $code = '';
  $characters = mt_rand(7,14);
  $i = 0;
  
  while($i &lt; $characters) 
  { 
  
      $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
      $i++;
  
  }
  
  $result = $db-&gt;query('
  SELECT uniqueID
  FROM '.$table.'
  WHERE uniqueID = "'.$code.'"
  LIMIT 1
  ');
  
  $totalRows = $result-&gt;num_rows;
  
  if(!$result)
  {
  
      return $db-&gt;error;
  
  }
  else
  {
  
      if($totalRows &gt; 0)
      {
  
          return uniqueID($table);
  
      }
      else
      {
  
          return $code;
  
      }
  
  }
  
  }
  </code></pre>