2016-04-21 60 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