按年和月获取数据库中的记录

时间:2014-01-30 08:27:23

标签: php mysql date

我这里有一个下拉列表,按年和月从数据库中选择记录。这适用于一年只有1个月。我需要的是将所有Januanry记录到6月的记录或7月到12月的记录。帮助

我的日期格式为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");

1 个答案:

答案 0 :(得分: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