简体   繁体   English

PHP MySQL获取日期之间的数据

[英]PHP MySQL Get data between dates

I have a simple code that I can't get to work. 我有一个简单的代码,我无法正常工作。 I'm trying to get all the data between selected dates but it isn't working. 我正在尝试获取选定日期之间的所有数据,但是它不起作用。 Here are my codes: 这是我的代码:

form 形成

 <form action="selectedInvoices.php" method="POST">
  <div class="row">
    <div class="large-4 columns">
      <label>From
        <input type="text" class="datepicker" name="from" />
      </label>
    </div>
    <div class="large-4 columns">
      <label>To
        <input type="text" class="datepicker" name="to" />
      </label>
    </div>
    <div class="large-4 columns">
      <button class="button" type="submit">Show Invoice</button>
    </div>
  </div>
  </form>

selectedInvoices.php selectedInvoices.php

$fromOrig = strtotime($_POST['from']);
$toOrig = strtotime($_POST['to']);

$from = date('Y-m-d', $fromOrig);
$to = date('Y-m-d', $toOrig);

$sql = mysql_query("SELECT * FROM allinvoices WHERE acc_date BETWEEN '".$from."' AND '".$to."'");
while($r = mysql_fetch_assoc($sql)) {
$drno = $r['drno'];
$name = $r['name'];
$amount = $r['amountdue'];

The data type of my acc_date field is varchar which I guess is wrong here. 我的acc_date字段的数据类型是varchar,我猜这里是错误的。 The format of the date when I insert is mdY. 插入日期的格式为mdY。

What should I do to make the code work? 我应该怎么做才能使代码正常工作? Thank you in advance. 先感谢您。

在此处输入图片说明

Since you said your date format in the database is mdY , you could simply change your $to and $from to the appropriate format. 由于您说数据库中的日期格式为mdY ,因此可以简单地将$to$from更改为适当的格式。

Replace 更换

$from = date('Y-m-d', $fromOrig);
$to = date('Y-m-d', $toOrig);

With

$from = date('m-d-Y', $fromOrig);
$to = date('m-d-Y', $toOrig);

And for your query, you can replace the BETWEEN with 对于您的查询,您可以将BETWEEN替换为

acc_date >= $from && acc_date <= $to
WHERE STR_TO_DATE(acc_date, '%Y/%m/%d')  BETWEEN '".$from."' AND '".$to."'

Fiddle 小提琴

Date in mysql is Ymd,you were comparing with dmY for BETWEEN.Also make sure $from is < than $to. mysql中的日期是Ymd,您正在将dmY与BETWEEN进行比较。还要确保$ from是<而不是$ to。

I recently worked on something similar. 我最近从事类似的工作。

I used the less than and more than operators, so 我使用了小于和大于运算符,所以

... WHERE startDate > $date AND endDate < $date

Also ensure that your date fields in the DB are actually proper date type fields. 还要确保数据库中的日期字段实际上是正确的date类型字段。 Make sure that when you insert a date, it's formatted correctly( IE. date type may be yyyy-mm-dd .) Otherwise the DB won't read it correctly. 确保插入日期时格式正确(即date类型可能是yyyy-mm-dd 。)否则,数据库将无法正确读取日期。

And just a side note, you can do away with the concatenation in your query by changing the surrounding quotes to single (the quotes around the whole query) 另外,您可以通过将周围的引号更改为单引号(整个查询的引号)来消除查询中的串联

 BETWEEN '".$from."' AND '".$to."'");

can become 可以变成

BETWEEN $from AND $to');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM