Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can either do this in PHP as you do or by using a MySQL trigger.</p> <p>If you stick to the PHP way, then instead of generating a number every time, do something like this</p> <pre><code>$found = 0; $cityarr = array(); $numberarr = array(); //create the cityarr for($i=1; $i&lt;=10;$i++) $cityarr[] = i; //create the numberarr for($i=1; $i&lt;=250;$i++) $numberarr[] = i; //shuffle the arrays shuffle($cityarr); shuffle($numberarr); //iterate until you find n unused one foreach($cityarr as $city) { foreach($numberarr as $num) { $sql_result2 = mysql_query("SELECT * FROM houses WHERE city='$city' AND number='$num'", $db); if (mysql_num_rows($sql_result2) == 0) { $found = 1; break; } } if($found) break; } </code></pre> <p>this way you don't check the same value more than once, and you still check randomly.</p> <p>But you should really consider fetching all your records before the loops, so you only have one query. That would also increase the performance a lot.</p> <p>like</p> <pre><code>$taken = array(); for($i=1; $i&lt;=10;$i++) $taken[i] = array(); $records = mysql_query("SELECT * FROM houses", $db); while($rec = mysql_fetch_assoc($records)) { $taken[$rec['city']][] = $rec['number']; } for($i=1; $i&lt;=10;$i++) $cityarr[] = i; for($i=1; $i&lt;=250;$i++) $numberarr[] = i; foreach($cityarr as $city) { foreach($numberarr as $num) { if(in_array($num, $taken[]) { $cityNotTaken = $city; $numberNotTaken = $number; $found = 1; break; } } if($found) break; } echo 'City ' . $cityNotTaken . ' number ' . $numberNotTaken . ' is not taken!'; </code></pre> <p>I would go with this method :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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