What are the potential pitfalls of sorting functions in PHP when dealing with numerical values in SQL queries?

When sorting numerical values in SQL queries using PHP, a potential pitfall is that the sorting may not work as expected if the numerical values are stored as strings in the database. To ensure proper sorting, you should cast the numerical values to integers or floats in your SQL query.

// Example of sorting numerical values in SQL query with proper casting

// Assuming $db is your database connection

$query = "SELECT * FROM table ORDER BY CAST(column_name AS SIGNED)";
$result = $db->query($query);

// Fetch and display results
while($row = $result->fetch_assoc()) {
    echo $row['column_name'] . "<br>";
}