What is the best practice for sorting SQL data in PHP in a descending order based on a specific ID?
To sort SQL data in PHP in a descending order based on a specific ID, you can use an SQL query with the ORDER BY clause. In this case, you would specify the ID column and use the DESC keyword to sort in descending order. You can then fetch the results in PHP using a database connection and execute the query.
// Database connection
$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 select data in descending order based on ID
$sql = "SELECT * FROM table_name ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Keywords
Related Questions
- How can PHP be used to centrally manage internal links on a website with many static pages?
- What best practices should be followed when including files in PHP scripts to avoid fatal errors like "Failed opening required"?
- How can non-programmers or individuals with limited technical expertise effectively manage and update content on a website built with PHP and a CMS like Typo3 or OctoberCMS?