Are there any potential pitfalls to be aware of when using the ORDER BY clause in PHP to sort data from a database table?

One potential pitfall to be aware of when using the ORDER BY clause in PHP to sort data from a database table is the risk of SQL injection if the input is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the ORDER BY clause.

// Example of using prepared statements with ORDER BY clause in PHP
$columnName = $_GET['column']; // Assuming user input for column name
$connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$statement = $connection->prepare("SELECT * FROM mytable ORDER BY $columnName");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

// Display the sorted results
foreach ($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}