【问题标题】:Get records in database by year and month按年和月获取数据库中的记录
【发布时间】:2026-01-11 23:45:01
【问题描述】:

我这里有一个下拉菜单,可以按年和月从数据库中选择记录。这可以正常工作,只有 1 个月。我需要的是按年获取所有一月到六月的记录或七月到十二月的记录。帮忙?

我的日期格式是 yyyy-mm-dd

<form id="form1" name="form1" action="<?php $_SERVER['PHP_SELF']?>" method="post">
<?php
$startYear = 2013;
$curYear = date('Y');
    echo'<select name="year">';
    foreach (range($startYear, $curYear) as $year) {
    echo '<option>'.$year.'</option>';
    }
    echo'</select>';

    echo'<select name="month">';
    for ($x=1; $x<=12; $x++)
    {
    $val=strlen($x);
    if($val==1)
    {
    echo '<option value="'.'0'.$x.'">'.'0'.$x.'</option>';
    } else {
     echo '<option value="'.$x.'">'.$x.'</option>';
    }
    }
    echo'</select>';
?>
<input type="submit" name="date" value="date"/>
</form>

<?php
    $year = $mysqli->real_escape_string($_POST["year"]);
    $month = $mysqli->real_escape_string($_POST["month"]);

    echo $year.'-'.$month;
    $result1 = $mysqli->query("SELECT po_date, rfq, shop, nego, shop, po_number, counter FROM purchase_order WHERE po_date LIKE '$year-$month-__' GROUP BY counter ORDER BY po_date");

【问题讨论】:

  • “po_date”字段的类型是什么?
  • @FezVrasta 类型为日期
  • 好的,请按照我链接的答案进行操作
  • @FezVrasta 但我的下拉列表的值如何?

标签: php mysql date


【解决方案1】:

如果要获取特定月份和年份的记录,请在日期字段上使用 monthyear 函数。

WHERE Year( po_date ) = $year
 and ( Month( po_date ) between 1 and 6    -- for JAN to JUN
       OR
       Month( po_date ) between 7 and 12   -- for JUL to DEC
     )

还有声明

Month( po_date ) between 1 and 6    -- for JAN to JUN
OR
Month( po_date ) between 7 and 12   -- for JUL to DEC

等价于

Month( po_date ) between 1 and 12    -- for JAN to DEC

因此你不应该在两个条件之间同时使用。
而是根据需要更改 between 子句的下边界值和上边界值。

示例 1
如果您想要aprilaugust 之间的记录,包括两者,请尝试

Month( po_date ) between 4 and 8    -- for APR to AUG, both inclusive

示例 2
如果您想要特定月份内的记录,例如“十月”,请尝试

Month( po_date ) = 10    -- for OCT

如果您仍想使用between 进行单月输出,请尝试

Month( po_date ) between 10 and 10   -- for OCT

【讨论】:

  • 我的答案也是在 MySQL 中。它不会影响您的数据,因为它只是一个select
  • 请不要使用您的答案来要求澄清,这可能会很混乱。这就是 cmets 的用途。
  • 谢谢,这样好多了:)
  • @Ravinder 可以解释一下吗?
  • @user3097736:如果您想检索一年中的第一或第二部分的记录,请在 between 子句中仅使用该周期。即使用month(po_date) between 1 and 6month(po_date) between 7 and 12 )
最近更新 更多