PHP MySQL按日期查询,递增/递减日期

时间:2014-02-21 19:24:11

标签: php html mysql web

我有一个带有时间表的数据库。 即

Class  Start     Day 
Yoga   9:00:00   1,2,3
Golf   13:00:00  2,5,6
etc...

其中星期一= 1,星期二= 2,       等

我现在可以很好地展示今天的活动,并希望添加一种方式来显示昨天(以及前一天,前一天等等)和明天(以及后天,和第二天......)

我一直在尝试使用Javascript和ajax(我开始学习任何类型的网页设计和语言)。在我看来,这应该是一个非常简单的任务,但我无法弄清楚我错过了什么。这是获取今天活动的代码:

<?php
//Create a connection
$con = mysqli_connect(
    "*********",            //host
    "*********",        //username
    "*********",            //password
    "*********"         //dbname
);

//check connection
if(mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//check if server is active
if(!mysqli_ping($con)){
    printf("Error: %s\n", mysqli_error($con));
}

$result = mysqli_query($con, "
    SELECT *
    FROM schedules
    ORDER BY Start ASC //Start time of event
");

/* print the Current Day in the Format:
    Day, Month, Year
*/
echo "<h1 align='center'>".date('l, F j, Y') . "</h1><br>";
//todays date
$current_day = date('N');

echo "<ul data-role='listview' data-inset='true'>";
while($row = mysqli_fetch_array($result))
{
    //if the event is on today then print the details
    if(strpos($row['Day'], $current_day) !== false){
        echo "<li>";

        echo "<h1>".$row['Start']." - ".$row['End']."</h1>";
        echo "<h2>".$row['Class']."</h2>";
        echo "<h2>".$row['Instructor']."</h2>";

        echo "</li>";
    }
}
echo "</ul>";

//close connection
mysqli_close($con)

1 个答案:

答案 0 :(得分:0)

更好的解决方案是将数据库中的这些字段分开,而不是将多个值存储在单个字段中。但是这是使用当前设计的方法。首先,定义一个昨天和明天的变量,注意不要溢出到0或8.我使用三元运算符来保持简洁:

 $yesterday = (($current_day-1)!=0) ? ($current_day-1) : 7;
 $tomorrow = (($current_day+1)!=8) ? ($current_day+1) : 1;

然后根据需要更新您的while块:

while($row = mysqli_fetch_array($result))
{
    //if the event is on today then print the details
    if(strpos($row['Day'], $current_day) !== false){
        echo "<li>";

        echo "<h1>".$row['Start']." - ".$row['End']."</h1>";
        echo "<h2>".$row['Class']."</h2>";
        echo "<h2>".$row['Instructor']."</h2>";

        echo "</li>";
    }

    if(strpos($row['Day'], $yesterday) !== false){
        //do stuff
    }

    if(strpos($row['Day'], $tomorrow) !== false){
        //do stuff
    }

}
echo "</ul>";