Jump to content

Need help in sorting date format (eg. July,2013)


holy24

Recommended Posts

Hi,I have created 2 fields in a table (month & year). The month will be shown as January,February,March etc. The year will be shown as 2011,2012 etc.The following is the code that will capture the date format once user submit a form.

<?php$jd=cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));$Month=jdmonthname($jd,1);$Year=date(Y);mysql_query ("INSERT INTO Table1 (month,year) VALUES ('$Month','$Year')");?>
Now, I have a problem in sorting the month in descending order (December,November,October etc). Can someone please kindly help me on the sorting and I need to make the month format remain as (December,November,October etc). Thanks.Below is the code to query the result, however it will sort by alphabetical order.
<?phpmysql_query ("Select * from Table1 where year='$Year' order by month DESC"); ?>?>

 

Link to comment
Share on other sites

If you stored the month as a number then you would be able to order it by month. MySQL doesn't know what order you think is correct for your strings.

 

You should store dates as numbers and only convert them to strings when you're displaying them to the user.

 

How to turn a number month into a text month:

 

// This is somewhere very early on in your code// The first slot is empty because there is no month 0 (zero)$months = array('Empty', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Whenever you need to print the month name $m = $row['month'];echo $months[$m];
Edited by Ingolme
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...