What SQL commands can be used to sort a table in ascending or descending order in PHP?
To sort a table in ascending or descending order in PHP, you can use the SQL commands "ORDER BY column_name ASC" for ascending order and "ORDER BY column_name DESC" for descending order. These commands can be added to a SQL query to retrieve data from a database table in the desired order.
// 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 select data from a table in ascending order
$sql = "SELECT * FROM table_name ORDER BY column_name ASC";
// Execute the query
$result = $conn->query($sql);
// Fetch and display the sorted data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column Value: " . $row["column_name"] . "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();