Hi I have a MySQL table that contains records of numbers i.e. products_num 1, products_num 2 now in the test table products
I tried to write a recursive function which check a randomly generated number against each products_num for no duplicates:
function gen_rand_products_num() {
$rand1 = mt_rand(1, 3); //rand gen 1, 2, or 3
$get_all_products_num = mysql_query("select products_num from products");
$num_of_products_nums = mysql_num_rows($get_all_products_num );
for ($i=0; $i<$num_of_products_nums; $i++) { //0 to 1 ($num_of_products_nums = 2)
if (!mysql_data_seek($get_all_products_num , $i)) {
continue;
}
if (!($row1 = mysql_fetch_assoc($get_all_products_num ))) {
continue;
}
if ((int)$row1['products_num'] != (int)$rand1) {
$rand_products_num = $rand1;
return $rand_products_num;
} else {
gen_rand_products_num();
}
}
}
echo gen_rand_products_num();
The function above is supposed to return a 3 only, that is not a duplicate of products_num 1 and products_num 2 of the products table.
But it still returns 1 or 2, along with 3. So please help me fix the function! Thanks in advance!