How can the PHP code be modified to display the results in the desired order (from bottom to top) based on the ID column in the MySQL table?
To display the results in the desired order (from bottom to top) based on the ID column in the MySQL table, you can modify the SQL query by adding "ORDER BY id DESC". This will sort the results in descending order based on the ID column. By doing this, the PHP code will display the results from the MySQL table in the desired order.
<?php
// Connect to MySQL 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);
}
// Select data from MySQL table in descending order based on ID
$sql = "SELECT * FROM table_name ORDER BY id DESC";
$result = $conn->query($sql);
// Display results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How can using the correct syntax for MySQL queries in PHP prevent errors and improve code functionality?
- What are some best practices for ensuring that user-entered values remain visible on a form after a calculation is executed in PHP?
- How can PHP beginners effectively organize and manage arrays to avoid confusion and errors during sorting?