What is the role of SQL in sorting data for display in an HTML table using PHP?

SQL can be used to sort data in a specific order before displaying it in an HTML table using PHP. By using the ORDER BY clause in your SQL query, you can specify which column to sort the data by and in what order (ascending or descending). This ensures that the data is displayed in a structured and organized manner in the HTML table.

<?php
// Connect to 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 table and order by a specific column
$sql = "SELECT * FROM table_name ORDER BY column_name ASC";
$result = $conn->query($sql);

// Display data in HTML table
if ($result->num_rows > 0) {
    echo "<table><tr><th>Column 1</th><th>Column 2</th></tr>";
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["column1"] . "</td><td>" . $row["column2"] . "</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$conn->close();
?>