如何在mysql查询php中回显当前日期

时间:2013-10-02 06:33:15

标签: php mysql date

当月开始

<?php echo date("Y-m-1");?>

当前月末

<?php echo date("Y-m-31");?>


and this is mysql query

$result = mysql_query("SELECT * FROM fuel where monthdate BETWEEN 'current month start' AND 'current month end' ORDER BY CAST(amount as SIGNED INTEGER) DESC LIMIT 4");

如何回应

<?php echo date("Y-m-1");?>

   <?php echo date("Y-m-31");?>

在这 在'{Y-m-1}'和'{Y-m-31}'之间

请帮我解决这个问题 感谢

4 个答案:

答案 0 :(得分:1)

您可以在纯SQL中轻松完成此操作,而无需在PHP中花费时间:

"SELECT * FROM fuel WHERE YEAR(monthdate) = YEAR(CURDATE()) AND MONTH(monthdate) = MONTH(CURDATE()) ORDER BY CAST(amount as SIGNED INTEGER) DESC LIMIT 4"

此外,您不能指望无效日期可以像这样工作。

在SQL查询中尝试此操作:

`SELECT DATE('2013-02-28'), DATE('2013-02-31')`

它将返回2013-02-28NULL。 MySQL期望VALID日期,否则它将无效。

答案 1 :(得分:1)

如果您需要查找当前年份和月份记录,可以使用mysql的EXTRACT函数,该函数为您提供当前月份并执行=比较

SELECT * FROM fuel where 
EXTRACT(YEAR_MONTH FROM `monthdate`) =
EXTRACT(YEAR_MONTH FROM CURRENT_DATE) 
ORDER BY CAST(amount as SIGNED INTEGER) 
DESC LIMIT 4

注意确保列monthdate数据类型正确,如date,datetime

EXTRACT

答案 2 :(得分:1)

Try this code woking fine.
$result = mysql_query("SELECT * FROM fuel where monthdate BETWEEN (SELECT DATE_FORMAT( NOW( ) , '%Y-%m-1' )) AND (SELECT DATE_FORMAT( NOW( ) , '%Y-%m-30' )) ORDER BY CAST(amount as SIGNED INTEGER) DESC LIMIT 4");

答案 3 :(得分:0)

如果您需要选择给定月份的所有内容,请使用date_format:

$myDate = date('Y-m');
$sql = "SELECT * FROM `fuel` WHERE DATE_FORMAT('%Y-%m', `monthdate`) = '$myDate'";