2016-12-04 76 views
0

,我需要選擇隨機行不重複,我使用下面的代碼,但收到警告:選擇隨機行不重複

mysqli_num_rows() expects parameter 1 to be mysqli_result 

請幫

<?php 
$servername = "localhost"; 
$username = "raffle"; 
$password = "raffle"; 
$dbname = "raffle"; 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
//code you provided 
$sql = "select staff_id, staff_name from 
(select DISTINCT staff_id, staff_name from dbo.[staff]) 
as derived1 ORDER BY RAND() 
LIMIT 1"; 
$result = mysqli_query($conn, $sql); 

if (mysqli_num_rows($result) > 0) 
{ 
    while ($row = mysqli_fetch_assoc($result)) 
    { 
     echo "$row[staff_id]", "$row[staff_name]"; 
    } 
} 
else 
{ 
    echo "none"; 
} 

mysqli_close($conn); 
?> 

請運行該代碼,並檢查

回答

0

LIMIT是你的朋友。 TOP 1不在MySQL中只有MSSQL。所以更改查詢來限制1,如:

$sql = "select staff_id, staff_name from 
(select DISTINCT staff_id, staff_name from dbo.[staff]) 
as derived1 ORDER BY RAND() 
LIMIT 1"; 
+0

感謝了很多,但警告仍然存在,我用你提供的查詢和獲取無 – user1873058

+0

@ user1873058 - 抱歉,我還沒有看到,你也必須改變** NEWID ()**到** RAND()** –

+0

不用擔心,還是一樣,請你檢查一下我的代碼(編輯過) – user1873058