0

在这里,我在 mysql 中有一个问题,即如何从当前日期到一周前查找值。在这里,我编写了一个程序,它应该显示当前日期和日期前一周之间的日期。

这是我的php代码:

<?php
$hostdb = 'localhost';
$namedb = 'my_db';
$userdb = 'root';
$passdb = 'root';

try {

  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8


$currDate = date('Y-m-d H:i:s');
$date = $currDate ;
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
//$offset = $dow - 3;
$offset = $dow - date('d');
if ($offset < 0) {
    $offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 1; $i++, $ts += 86400){
    //print date("Y-m-d l", $ts) ."</br>" . "\n";
$week = date("Y-m-d H:i:s", $ts) ."</br>";

}


  $sql = "SELECT * FROM battery WHERE date BETWEEN " . $date .  " AND " . $week;


  $result = $conn->query($sql);

echo "<table border='1' style='font-family:arial;font-size12px;' cellspacing=1>
<tr>
<th>User Id</th>
<th>Firstname</th>
<th>LastName</th>
<th>EmailId</th>
<th>Date</th>
</tr>";

  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
  echo "<tr>";

  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['emailid'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";

  echo "</tr>";
  }

echo "</table>";

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();

}

?>

这里 $date 给出当前日期, $week 给出日期前一周。我无法在这两个日期之间找到价值。请,我需要一些帮助。任何帮助将不胜感激。

4

3 回答 3

0

您可以在 php.ini 中使用 DateTime 和 DateInterval 类。

http://www.php.net/manual/en/class.datetime.php http://www.php.net/manual/en/class.dateinterval.php

于 2013-05-08T10:17:27.023 回答
0

我相信这里的答案可能会有所帮助:MySQL Query - Records between Today and Last 30 Days

您可以将过去 30 天更改为过去 7 天(如果仅在星期五运行,则可以更改为 5 天?:))

于 2013-05-08T10:08:57.833 回答
0

你可以使用 mysql 中的datediff方法来做到这一点。

SELECT * FROM battery WHERE DATEDIFF(now(), `date`)<=6 AND DATEDIFF(now(), `date`)>=0
于 2013-05-08T10:11:49.340 回答