Jump to content

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?

I i total or sum all the float value using SQL statement, the total result will not accurate.

 

Just for an example:

10.6 + 12.8 = 23.4

 

but if you use SQL statement to sum it, it will output somethings like 23.3522222.(just for example).

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.