2011-12-18 64 views
0

我想選擇MySQL表中的所有條目,並隨機顯示其中的一些條目。 這裏是我的代碼:檢索特定的mysql結果行

include 'connectdb.php'; 

$query = "SELECT * FROM places WHERE box = 1"; 
$result = mysql_query($query); 
$total = mysql_affected_rows(); 
$total = $total - 1; 
$wanted = 2; // the number of entries i want to display 
if($wanted > $total) { 
    die("Not enough places yet!"); 
    } 
$toshow = array(); 
for($i = 0; $i < $wanted ; $i++) { 
    $temp = rand(0 , $total); 
    while(in_array($temp , $toshow)) { 
     $temp = rand(0 , $total); 
     } 
    $toshow[$i] = $temp; 
    } 
foreach($toshow as $add){ 
    $row = // function needed here // 

    $name = $row['name']; 
    $telephone = $row['telno']; 
    //get rest of row and include a view to show the entry 
    } 

我也嘗試使用:

mysql_result($result , $add); 

,但似乎並沒有幫助。 MySQL連接的工作原理是,for循環返回一個只存在一次的數字數組,這樣我就不會一直顯示相同的帖子,而且我添加了模子,因爲如果我們需要更多的帖子而不是數字,它困在一個無限循環中。

關於函數的任何想法我需要/建議來解決問題? /我做的事情完全錯了?

回答

2

以隨機順序只需選擇與你已經擁有你所求的:

$query = sprintf("SELECT * FROM places WHERE box = %d ORDER BY RAND() LIMIT 0, %d" 
        , 1, $wanted); 
+0

爲什麼特別'LIMIT 1'? – zerkms 2011-12-18 05:49:27

+0

這是一個錯誤,它是限制0,$想要的。 – hakre 2011-12-18 05:50:33

+0

他們應該把錢放在臉上。謝謝! – ppp 2011-12-18 12:59:11