2013-03-12 66 views
2

我不明白爲什麼我的代碼不能正常工作。該連接工作和其他一切但是當我嘗試生成一個唯一的隨機數,並從MySQL檢查數量是有它仍然打印出一個隨機數,但它不是唯一的。任何人都可以幫助我嗎? 這裏是我的代碼:PHP MySQL的生成唯一的隨機數

$num = rand(1,5); 
$sel_query = "SELECT * FROM test"; 
$result2 = $con->query($sel_query); 

$i = 1; 
for (;$i<2; $i++) 
{ 
    while($row = mysqli_fetch_array($result2)) 
    { 
     if ($row['id'] == $num) 
     { 
      $num = rand(1,5); 
      $i = 0; 

     } 
    } 
} 
+0

什麼是蘭特的列這就是我想要做的,但數量在DB你可以簡單地做它的搜索,而不是循環通過...... – 2013-03-12 04:14:52

+0

它不工作@艾倫 – user2138160 2013-03-12 04:14:58

+0

這可以幫助你: http://stackoverflow.com/問題/ 8834493 /如何-生成唯一的隨機數功能於PHP – 2013-03-12 04:19:10

回答

1

這應該工作:

$is_unique = false; 
$num = false; 
while (!$is_unique){ 
    $num = rand(1,5); 
    $sel_query = "SELECT id from test where id = " . $num; 
    $result2 = $con->query($sel_query) or die($conn->error); 
    if (!mysqli_fetch_array($result2)){ 
     $is_unique = true; 
    } 
} 
echo "Unique number is " . $num; 

但如果沒有任何更多的可能唯一的數字,它會永遠循環下去。

+0

我得到了一個錯誤:警告:mysqli_fetch_array()預計參數1被mysqli_result,在 – user2138160 2013-03-12 05:14:36

+0

定的boolean有某種錯誤呢。我編輯了它,現在嘗試它,它應該輸出錯誤。 – Jodes 2013-03-12 05:41:23

0

我知道這是有點老了,但我發現這個問題,需要一個類似的答案後。我已經採取了Jodes的答案,稍微更新它,所以它不會永遠運行下去,是返回數的功能,並接受mysqli的連接爲$ mysqli的:

function getUniqueNumber($mysqli) 
{ 
    $is_unique = false; 
    $num = false; 
    $times_run = 0; 
    while (!$is_unique) 
    { 
     if($times_run > 10) 
     { 
      echo "Run too many times, dying."; 
      die(); 
     } 
     $num = rand(1,5); 
     $sel_query = "SELECT id from test where id = " . $num; 
     $result2 = $mysqli->query($sel_query) or die($mysqli->error); 
     if (!mysqli_fetch_array($result2)) 
     { 
      $is_unique = true; 
     } 
     $times_run++; 
    } 
    return $num; 
}