2016-04-21 59 views
-2

我想從我的數據庫中獲得三個具有最高值的實體,對它們進行排序並將它們放在每個div中,就像前三名的記分板一樣。我也將能夠分隔字段(ID,名稱,說明等)和檢索那些通過使用例如:使用mysql/php對前三名排序

<?php echo $sql['id']; ?> 

我已經知道的代碼來獲取信息,並對其進行排序:

$sql = ("SELECT * FROM table ORDER BY tablefield DESC LIMIT 3"); 

但我不知道如何將三個實體放入他們的每一個div的和獨立實體的領域,如名稱,說明等

+0

沒什麼神奇的:while($ row =從結果中獲取){echo'

'; echo $row stuff; echo '
'; }' –

+0

如果您剛剛開始使用PHP開發並希望創建應用程序,請選擇[Laravel] [0124] (http://laravel.com/),適合您的風格和需求。這些附帶的例子說明了如何做到你在這裏要求的。 – tadman

回答

1

如果你正在使用MySQL(PDO),我強烈建議,那麼它的完成如下:

$sql = "SELECT * FROM table ORDER BY tablefield DESC LIMIT 3"; 
$stmt = $conn->prepare($sql); 
$stmt->execute(); 

/*here you get a multidimentional array with the information you wanted*/ 
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 


//this would be one method of extracting the information 
//If you want to place them in specific divs as your 
//question suggests, then you could just use the array 
//inside the divs instead than echoing them out in 
//this foreach loop 

foreach ($rows as $row) 
{ 
    foreach ($row as $key => $value) 
    { 
    echo $key.": ".$value."<br>"; 
    } 
    echo "<br>"; 
} 

/*alternatively you could just use: 

print_r($rows); 

if you just want to have a quick look at the 
composition of the array*/ 
+0

通常,prepare()調用的結果被稱爲語句或文檔中使用的$ stmt。在這裏更短可能會更好。 – tadman

+0

@tadman感謝您的觀察!清潔更好 – Webeng

+0

現在看起來不錯。按照慣例,稍後會導致更少的意外。 – tadman