Jump to content

Archived

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

EricgTP313

Sorting by numbers..."123" is less than "99"

Recommended Posts

Hello,
I've written a very basic shopping cart script in php/mysql for a friend, and I want to be able to sort by price ascending and descending, but if there is a price that is, say $123, it is being sorted as less than, say, $99, because the 1 obviously IS less than the 9.

How would I go about making the script know that a 1 in a 3 digit string actually is greater than a 9 in a 2 digit string, and so on?
Heres my code:
[code]

<?php
$sort = $_GET['sort'];
$by = $_GET['by'];

if(!$sort){
$sort = title;
}
if(!$by){
$by = ASC;
}

$query2 = mysql_query("SELECT * FROM products WHERE type = 'sfx' ORDER BY $sort $by") or die(mysql_error());
?><div align="right">
<form name="form1" id="form1">Sort Items By:
  <select name="menu1" onchange="MM_jumpMenu('parent',this,0)">
  <option value="#">[Select One]</option>
    <option value="index.php?p=sfx&sort=price&by=DESC">Price (High - Low)</option>
<option value="index.php?p=sfx&sort=price&by=ASC">Price (Low - High)</option>
<option value="index.php?p=sfx&sort=title&by=ASC">Title (A - Z)</option>
<option value="index.php?p=sfx&sort=title&by=DESC">Title (Z - A)</option>
<option value="index.php?p=sfx&sort=type&by=ASC">Type (A - Z)</option>
<option value="index.php?p=sfx&sort=type&by=DESC">Type (Z - A)</option>
  </select>
</form>
</div>
[/code]

Share this post


Link to post
Share on other sites
Use this instead after echoing the results:

[code]<?php
sort($array, SORT_NUMERIC);
?>[/code]

Share this post


Link to post
Share on other sites
Also, shouldn't the values of the variables $sort and $by be in quotes? Unless you defined title and ASC as constants...

And your query should work fine.

Share this post


Link to post
Share on other sites
Change the column type for price so that it will be sorted correctly.
[code]
ALTER TABLE products CHANGE price price DECIMAL
[/code]
If you're storing the "$" symbol in the column you should stop doing so.

Share this post


Link to post
Share on other sites
[quote author=shoz link=topic=99897.msg393711#msg393711 date=1152391726]
Change the column type for price so that it will be sorted correctly.
[code]
ALTER TABLE products CHANGE price price DECIMAL
[/code]
If you're storing the "$" symbol in the column you should stop doing so.
[/quote]

awesome, that worked great, thanks!
and no, I'm not storing the $ in the column :)

Share this post


Link to post
Share on other sites

×

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.