2014-02-21 102 views
0

我有一個帶時間表的數據庫。 即PHP MySQL按日期查詢,遞增/遞減日期

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) 

回答

0

更好的解決方案是將數據庫中的這些字段分開,而不是將多個值存儲在單個字段中。但是,有一種方法可以使您的當前設計符合您的要求。首先,定義了昨天和明天的變量,小心不要溢出到0或8我使用三元運算以保持其簡潔:

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

然後根據需要更新,而塊:

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>"; 
+0

這在PHP方面很有意義。 對於客戶端來說,我似乎無法讓它在昨天或明天設置。 – donlonc

+0

你想讓客戶端的輸出看起來像什麼? – larsAnders

+0

我希望在頭部導航欄中有三個按鈕,昨天,今天和明天有一個按鈕。它會在當天顯示事件。一旦明天被點擊,它會在第二天顯示,如果明天再次點擊,它會在第二天顯示。 目前我只是在星期一至星期日的菜單中使用表格。我只是覺得按鈕選項會更乾淨。 – donlonc