How can the ORDER BY clause be used effectively in SQL queries when fetching data in PHP?

When fetching data in PHP using SQL queries, the ORDER BY clause can be used to sort the results based on a specific column or columns. This can be useful when you want to retrieve data in a specific order, such as alphabetically or numerically. To use the ORDER BY clause effectively, simply include it in your SQL query along with the column you want to sort by and the desired sorting order (ASC for ascending or DESC for descending).

// 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 with ORDER BY clause
$sql = "SELECT * FROM table_name ORDER BY column_name ASC";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column Name: " . $row["column_name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();