What best practices should be followed when executing SQL queries in PHP to ensure proper sorting of data?

When executing SQL queries in PHP to retrieve data, it is important to specify the desired sorting order in the query itself using the ORDER BY clause. This ensures that the data is returned in the correct order as per the specified criteria. Additionally, it is recommended to validate and sanitize user input to prevent SQL injection attacks.

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

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

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

$conn->close();
?>