Sorting top three using mysql/php

时间:2016-04-21 21:52:02

标签: php html mysql database limit

I want to get the three entities with highest value from my database, sort them and place them in each their div's just like a scoreboard with the top three. I will also be able to separate the fields (id, name, description etc.) and retrieve those by using for example:

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

I already know the code to retrieve the info and sort it:

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

But I don't know how to place the three entities into each their div's and separate the entity's fields like name, description etc.

1 个答案:

答案 0 :(得分:1)

if you are using MySQL (PDO), which I highly recommend, then it's done as follows:

$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*/