如何让这个PHP脚本对Descending进行排序?

时间:2016-12-25 17:44:11

标签: mysql sorting

 <?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Name</th><th>Experience</th></tr>";

class TableRows extends RecursiveIteratorIterator { 
    function __construct($it) { 
        parent::__construct($it, self::LEAVES_ONLY); 
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() { 
        echo "<tr>"; 
    } 

    function endChildren() { 
        echo "</tr>" . "\n";
    } 
} 

$servername = "xxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxxx";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT Name, sum(Experience) FROM Hunters GROUP BY Name         ORDER BY Experience DESC"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

我试图通过体验降序来排序,但它只是没有做到。我不确定如何制作它。任何帮助将不胜感激。这是为了显示体验点。

1 个答案:

答案 0 :(得分:1)

如果您使用此功能的聚合函数排序

SELECT Name, sum(Experience) 
FROM Hunters 
GROUP BY Name  
order by sum(Experience) DESC 

或者如果db版本支持您可以使用别名

SELECT Name, sum(Experience) tot_experience 
FROM Hunters 
GROUP BY Name  
order by tot_experience  DESC