title: MySQLi creating random string, but checking it doesn't already exist
body: <p>Below is my code that i have written to create a random string. Works well. It also checks to make sure that the generated string doesn't already exist, and if it does, then it makes another one. HOWEVER i haven't yet worked out a way to make the code generated if one already exists be checked to see if that one exists. Would i be best doing an elseif statement?</p>
  
  <p>PHP</p>
  
  <pre><code>&lt;?PHP
  require_once('dbConfig.php');
  $randomstring = '';
  $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  
  for ($i = 0; $i &lt; 12; $i++) {
      $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }
  //$generatedId = "SPI-E7HN2SBIIF5W";
  $generatedId = 'SPI-'.$randomString;
  
  //Prepare select query
  $statement = $db-&gt;prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
  
  //Determine variable and then bind that variable to a parameter for the select query ?
  $id = $generatedId;
  $statement-&gt;bind_param('s', $id);
  
  //Execute and store result so that num_rows returns a value and not a 0
  $statement-&gt;execute();
  $statement-&gt;store_result();
  
  //Bind result to a variable for easy management afterwards
  $statement-&gt;bind_result($clientId);
  
  // Generate a random ID for the user if the previously generated one already exists
  if($statement-&gt;num_rows &gt; 0){
      $randomstring = '';
      $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  
      for ($i = 0; $i &lt; 0; $i++) {
          $randomString .= $characters[rand(0, strlen($characters) - 1)];
      }
      $generatedId = 'SPI-'.$randomString;
      echo $generatedId;
  } else {
      // If there's no issue with what's been created, echo it out :)
      echo $generatedId;
  }
  
  
  ?&gt;
  </code></pre>
  
  <p>Any help is appreciated :)</p>