Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First of all, the direct error in your code is</p> <pre><code>if(mysql_num_rows($result) == 1) { $rrezervim_id = rand(1, 5); } </code></pre> <p>fails, if you hit a taken number <strong>twice</strong>. You need a loop, such as </p> <pre><code>while (mysql_num_rows($result) == 1) { $rrezervim_id = rand(1, 5); $result = mysql_query("SELECT rrezervim_id FROM pax_list WHERE rrezervim_id='$rrezervim_id'"); } </code></pre> <p>That said, I suspect, that there is more wrong with your code:</p> <ol> <li><p>If you want to use this "free" random number to insert it into the database at a later point in time, you are wide open to a race condition: Both processes select the same (still free) number, but only on the first insert is it still unique. </p></li> <li><p>This approach can have extremely bad performance, if your field of possible random numbers is nearly full: If you have 80% fill rate, such as in your example, you will on average have 4 "bad" hits, before getting a "good" hit.</p></li> </ol> <p>I recommend you consider using a database built-in, such as the battle-proven AUTO_INCREMENT as a primary means, then use a formula to create the hard-to-guess pseudo-random from it. <a href="http://en.wikipedia.org/wiki/LFSR" rel="nofollow">A linear feedback shift register</a> can be one approach, while cryptographically combining the auto-generated ID and a (not necessarily unique) pseudo-random stored in the table might be another. Both methods give you linear performance and race-free usage.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload