Jump to content

php sorting problem usng SQL ORDER BY


peterjc

Recommended Posts

i have a sorting problem in php using the SQL command "ORDER BY".

 

-----------------

For example:

i want to sort this number descending: 30, 4, 50, 200.

 

so in actual case we should get: 200 , 50, 30 , 4.

 

But what i get when using the ORDER BY statement is: 50, 4, 30, 200

 

-------------------

After look a while at the incorrect result, i think the problem is because it sort using the first digit of the number.

 

Anyone know how to solve this problem?

 

Thank in advance.

Link to comment
https://forums.phpfreaks.com/topic/68651-php-sorting-problem-usng-sql-order-by/
Share on other sites

Oh.  corbin, i use the char datatype for the number. i just realize it. 

 

At first i use float number datatype, but i change to char because when we total up the float number, there will be some inaccurate in php, am i correct?  How to solve this?

The other option is

 

ORDER BY CAST(foo AS UNSIGNED)

 

What happens when you add 0 to foo is that mysql is forced to convert foo into an integer.  After that, it is sorted as an integer.  The same happens when you explicitly cast foo to an integer using CAST().  "Cast" means "Change from one type to another".

 

The original problem is that your numbers were being sorted as strings, which is why it looked at the first character first, then second, and so on.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.