title: How generate UNIQUE random number in php
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/319524/algorithm-for-generating-a-random-number">Algorithm for generating a random number</a>  </p>
  </blockquote>
  
  
  
  <p>Hi i need to assign a randomly generated number to some entries into the database and it must be unique.
  I use:</p>
  
  <pre><code>$random_number = mt_rand();
  mysqli_query($db_connection, "INSERT INTO my_table (rand_num, blabla) VALUES ('$random_number', '$blabla')");
  </code></pre>
  
  <p>But ofc there could always be a slightly low chance that 2 random numbers will be the same.
  Then i could do something like:</p>
  
  <pre><code>function random_check($random_number) {
      require_once('db_access.php');
      $random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
      mysqli_close($db_connection);
      $result = 1;
      while($row = mysqli_fetch_array($random_check)){
              if ($row['rand_num'] == $random_number) {
               $result=0
             }
      }
          return $result;
  };
  
  $random_number = mt_rand();
  $random_check = random_check($random_number);
  if ($random_check == 0) {
        $random_number = mt_rand();
  }
  </code></pre>
  
  <p>But this would only check the number once and there will still be a chance that the new generated number already exists into the db.</p>
  
  <p>Any suggestions?
  Thanks</p>