根据PHP时间戳过滤数据

时间:2014-12-30 12:54:16

标签: php mysql

我有一张这样的表

|---------|--------------------|---------------------|-------------------|
|   id    |   first_name       |    last_name        |     timestamp     |
|------------------------------------------------------------------------|
|    1    |     Saswat         |      Routroy        |    12098345765    |
|------------------------------------------------------------------------|
|    2    |     Tuhin          |       Paul          |    12098565765    |
|------------------------------------------------------------------------|
|    3    |     Tuhina         |       Paul          |    12098565455    |
|------------------------------------------------------------------------|
|    4    |     Sabina         |       Khatun        |    12098578955    |
|------------------------------------------------------------------------|
|    5    |     Shajid         |       Daruwala      |    12098598455    |
|________________________________________________________________________|

此处时间戳字段在此方法中具有值

$timestamp = time();

因此插入数据库......

现在,我需要过滤此选项的数据

today,
yesterday,
last seven day,
this month.

这是我的剧本

$dt_table = "td_user";
    $arr_result = array();
    $sql = "SELECT id,timestamp,first,last,company_name,company_size FROM td_user LIMIT $start_row , $limit";
    $result = mysql_query($sql);
    $tot_data = 0;


    if($time_type == "today")
    {
        while($row = mysql_fetch_assoc($result))
        {
            $data_timestamp = $row['timestamp'];
            $date = date('Y-m-d', $data_timestamp);
            $today = date('Y-m-d');
            if ($date == $today) 
            {
                $arr_result[] = $row;
            }
        }
    }
    else if($time_type == "yesterday")
    {
        while($row = mysql_fetch_assoc($result))
        {
            $data_timestamp = $row['timestamp'];
            $midnightYes = strtotime("midnight yesterday");
            $midnightToday = strtotime("midnight today");
            if ($data_timestamp > $midnightToday) 
            {
                //today
            } 
            else if($data_timestamp > $midnightYes && $data_timestamp < $midnightToday) 
            {
                $arr_result[] = $row;
            }
        }
    }
    else if($time_type == "last_seven_day")
    {

    }
    else if($time_type == "last_month")
    {

    }

现在,我已经成功检索了今天和昨天的数据......但是如何从last seven daysthis month获取数据?

2 个答案:

答案 0 :(得分:1)

如果你想使用strtotime,你有:

$last = strtotime('last week');
$month = strtotime('this month');

您有文档:http://php.net/manual/en/function.strtotime.php

答案 1 :(得分:0)

使用DATE和CURDATE()

SELECT * FROM table WHERE DATE(timestamp)= CURDATE()

我想使用DATE仍然使用INDEX。

see the execution plan on the DEMO