显示数据库中的数据,其中日期在本周内

时间:2015-08-26 16:05:53

标签: php database date if-statement dayofweek

我这里有一个代码,用于在本周内的一天内获取数据库中的数据。例如:如果今天的日期是2015-08-27,并且数据库中的date_paid列的值为2015-08-26和2015-08-25,则它将显示具有这些日期之一的数据。 这是我尝试获取本周内日期的代码:

// set current date
$date = date('Y-m-d');
// parse about any English textual datetime description into a Unix timestamp 
$ts = strtotime($date);
// find the year (ISO-8601 year number) and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
for($i = 1; $i <= 7; $i++) {
    // timestamp from ISO week date format
    $ts = strtotime($year.'W'.$week.$i);
    //shows the date for 7days
    $week[$i] = date("Y-m-d", $ts) . "<br>";
}

if($week[1] == $date)
{
    $today = $week[1];
}

if($week[2] == $date)
{
    $today = $week[2];
}

if($week[3] == $date)
{
    $today = $week[3];
}

if($week[4] == $date)
{
    $today = $week[4];
}

if($week[5] == $date)
{
    $today = $week[5];
}

if($week[6] == $date)
{
    $today = $week[6];
}

if($week[7] == $date)
{
    $today = $week[7];
}

$transaction = mysqli_query($connection, "SELECT * FROM transaction WHERE date_paid = '$today'");
$counttrans = mysqli_num_rows($transaction);

此代码假设获取具有该周日期的数据。但它不起作用。任何人都可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要获取date_paid的日期。使用MySQL函数'WEEKDAY'

  

返回日期的工作日索引(0 =星期一,1 =星期二,... 6 =星期日)。

这是一个例子。

select users.created_at as day_of_week, WEEKDAY(users.created_at)  
from users;
+---------------------+---------------------------+
| day_of_week         | WEEKDAY(users.created_at) |
+---------------------+---------------------------+
| 2015-08-26 05:22:29 |                         2 |
| 2015-08-04 14:14:32 |                         1 |
+---------------------+---------------------------+

我们将通过执行此查询来选择在第1天创建的用户

select users.created_at as day_of_week  
from users  
where WEEKDAY(users.created_at) = '1';
+---------------------+
| day_of_week         |
+---------------------+
| 2015-08-04 14:14:32 |
+---------------------+

在您的情况下,您的查询应该如下所示

"select transaction.date_paid as pay_day
 from transaction
 where WEEKDAY(transaction.date_paid ) =". $day;