[英]Convert month number to month name with sql
In my database the column "monthnumber" (varchar) indicates the month. 在我的数据库中,“ monthnumber”列(varchar)指示月份。 (1 = january , 12 = december) Now I need to echo the name of the month instead of the number. (1 = 1月,12 = 12月)现在,我需要回显月份的名称而不是数字。
I already found some examples and it seems that using DateName( )
is the correct way to do this kind of stuff. 我已经找到了一些示例,似乎使用DateName( )
是执行此类操作的正确方法。 But even with these examples, it's not working for me. 但是即使有这些示例,它也不适用于我。 Apparently I'm missing something but I can't figure out what... 显然我缺少了一些东西,但我不知道是什么...
.htaccess file: .htaccess文件:
RewriteRule ^example/([^/]+)/([^/]+)$ test?year=$1&monthnumber=$2 [L,QSA]
Html/php: HTML / PHP:
<?php
$year= $_GET['year'];
$monthnumber= $_GET['monthnumber'];
$sql = "SELECT DISTINCT DateName( month, DateAdd( month , 'monthnumber' , -1 ) ) AS 'monthname', monthnumber, year FROM `exampletable` WHERE year = :year AND monthnumber = :monthnumber";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":year", $year);
$stmt->bindParam(":monthnumber", $monthnumber);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<?php echo strtolower($result['monthname']);?> <?php echo $result['year'];?>
<?php
}// end if
else {
echo '0 results';
}// end else
?>
Some row examples (year monthnumber) 一些行示例(年月号)
(2014 8), (2014 7), (2013 8), ... (2014 8),(2014 7),(2013 8),...
When I try to open example.com/2014/8
, it gives me "0 results" instead of "August 2014", while my old code (month displayed as number) works: 当我尝试打开example.com/2014/8
,它给了我“ 0结果”而不是“ 2014年8月”,而我的旧代码(以数字显示的月份)有效:
$sql = "SELECT DISTINCT monthnumber, year FROM `exampletable` WHERE year = :year AND monthnumber = :monthnumber";
This is your query: 这是您的查询:
SELECT DISTINCT DateName( month, DateAdd( month , 'monthnumber' , -1 ) ) AS monthname,
monthnumber, year
FROM `exampletable`
WHERE year = :year AND monthnumber = :monthnumber
It is using functions from SQL Server, so I doubt this will work in MySQL. 它正在使用SQL Server中的函数,因此我怀疑这是否可以在MySQL中使用。
You are better off just using a case
statement: 您最好只使用一个case
语句:
select distinct (case when monthnumber = '1' then 'January'
when . . .
when monthnumber = '12' then 'December'
end) as monthname
from exampletable
where year = :year and monthnumber = :monthnumber;
You can also do this by constructing a date and using monthname()
: 您还可以通过构造一个日期并使用monthname()
来做到这一点:
select distinct monthname(date(concat_ws('-', year, monthnumber, '01'))) as monthname
from exampletable
where year = :year and monthnumber = :monthnumber;
Note: you should only use single quotes for date and string constants. 注意:您只能对日期和字符串常量使用单引号。 Never use single quotes around column names, it will just lead to problems. 永远不要在列名周围使用单引号,否则只会导致问题。
在MySql中,只需使用以下语句将数字转换为月份(工作示例)
SELECT MONTHNAME(STR_TO_DATE(id,'%m')) as nameofmonth FROM `user`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.