How can SQL be used to retrieve and sort data from a database table in PHP for generating a sorted ranking table?
To retrieve and sort data from a database table in PHP for generating a sorted ranking table, you can use SQL queries to fetch the data from the database and specify the sorting criteria. You can use the ORDER BY clause in your SQL query to sort the data based on a specific column in ascending or descending order. Once you have fetched the sorted data, you can display it in a table format to create a ranking table.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve and sort data from the database table
$sql = "SELECT * FROM ranking_table ORDER BY score DESC";
$result = $conn->query($sql);
// Display the sorted data in a table
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr><th>Rank</th><th>Name</th><th>Score</th></tr>";
$rank = 1;
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $rank . "</td><td>" . $row["name"] . "</td><td>" . $row["score"] . "</td></tr>";
$rank++;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Related questions
-
PHP dropdown menu server differentiation
-
data integrity special characters output consistency
-
PHP database interaction data display