What steps should be taken to ensure the proper functioning of PHP code that retrieves and displays data from a database for a ranking system?
To ensure the proper functioning of PHP code that retrieves and displays data from a database for a ranking system, it is important to properly establish a connection to the database, execute the query to retrieve the necessary data, and handle any errors that may occur during the process. Additionally, the retrieved data should be displayed in a clear and organized manner to accurately represent the ranking system.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute query to retrieve data for ranking system
$sql = "SELECT * FROM ranking_table ORDER BY score DESC";
$result = $conn->query($sql);
// Display retrieved data in a table format
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 "No data found";
}
// Close database connection
$conn->close();
?>