Monday, July 9, 2012

MySQL ORDER BY MONTH

MySQL ORDER BY MONTH


Month Names in year are not in alphabetically ordered.So you will be faced problem of ordering month name.But when you insert a number instead of month name in to MySQL table  could resolve the problem.ex:- January=1,February=2, March=3 etc.Create following table called progress1

CREATE TABLE IF NOT EXISTS `progress1` (
  `id` int(30) NOT NULL AUTO_INCREMENT,
  `Month` varchar(60) NOT NULL,
  `Production` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ;

--
-- Dumping data for table `progress1`
--

INSERT INTO `progress1` (`id`, `Month`, `Production`) VALUES
(13, '1', '20'),
(14, '2', '21'),
(15, '3', '45'),
(16, '4', '54'),
(17, '5', '56'),
(18, '6', '67'),
(19, '7', '34'),
(20, '8', '98'),
(21, '9', '12'),
(22, '10', '33'),
(23, '11', '45'),
(24, '12', '53');


Then create following php file and ypu will get the results in month name in order

<?php
echo "<center><table bgcolor=#0b2d04>
<tr bgcolor=#327423>
<th><font color=#ffffff>Month</font></th>
<th><font color=#ffffff>Number of Products</font></th>
</tr>";
$username="root";
$password="";
$database="my_database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query ="(SELECT * FROM progress1 ORDER BY ABS('Month') ASC)";
$result = mysql_query($query);
mysql_close();
while ($row = mysql_fetch_assoc($result)){
$month=$row['Month'];
if ($month == "1") {
$month_name = "January";
} else if ($month == "2"){
$month_name = "February";
} else if ($month == "3"){
$month_name = "March";
} else if ($month == "4"){
$month_name = "April";
}else if ($month == "5"){
$month_name = "May";
} else if ($month == "6"){
$month_name = "June";
} else if ($month == "7"){
$month_name = "July";
}else if ($month == "8"){
$month_name = "August";
} else if ($month == "9"){
$month_name = "September";
} else if ($month == "10"){
$month_name = "October";
}else if ($month == "11"){
$month_name = "November";
} else if ($month == "12"){
$month_name = "December";
}
echo "<tr  bgcolor=#d7eecb>

<td>" .$month_name."</td>

<td>" .$row['Production']."</td>
</tr>";
}
echo "</table></center>";
?>
Month Number of Products
January 20
February 21
March 45
April 54
May 56
June 67
July 34
August 98
September 12
October 33
November 45
December 53

No comments:

Post a Comment