从mysql timestamp字段中选择Distinct month和year,并在php中回显它们

问题描述:

My mysql table has a createdOn column with filedtype 'timestamp' in the format of 2011-10-13 14:11:12.

What I need is to show, is distinct month,year from createdOn column.

I have searched on stackover flow and was able to echo back months using following code,

*$sqlCommand = "SELECT DISTINCT MONTH(createdOn) AS 'Month' FROM videoBase ORDER BY createdOn DESC";
$query=mysqli_query($myConnection,$sqlCommand) or die(mysqli_error());
while($row = mysqli_fetch_array($query)) {
    $date = date("F", mktime(0, 0, 0, $row['Month']));
    echo ''.$date.' <br />';
}*

This outputs months as :

October
January

What I need is the output in the format of:

October 2011
January 2012

Can anybody please let me know, what changes I should make in the code in order to get the required output.

Thanks

Use this:

$date = date("F Y", strtotime($row['Month']));

and in your query don't select the month, just:

SELECT DISTINCT createdOn AS 'Month' FROM videoBase ...

So it will be:

$comma = '';
while($row = mysqli_fetch_array($query)) {
    $date = $comma . date("F", mktime(0, 0, 0, $row['Month']));
    echo $comma . $date;
    $comma = ', ';
}

try below for current year

 echo $date.date("Y");

OR if you want specific year then you must have to take from database table

Thanks

For a MySQL solution:

SELECT DISTINCT CONCAT(MONTHNAME(createdOn), ' ', YEAR(createdOn)) AS `Month`
FROM videoBase
ORDER BY createdOn DESC

This takes the output of the MONTHNAME() function and YEAR() function and concatenates them with a space between, like this:

October 2011
January 2012