2015-08-26 42 views
0

我在這裏有一個代碼,用於在本週內獲取數據庫中的數據。例如:如果今天的日期是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); 

此代碼假設來獲取具有該週一天的數據。但它不起作用。任何人都可以修復這個

+0

你能不能請你說的更詳細它不起作用?預期的結果是什麼,當前代碼的實際結果是什麼? –

+0

它不能正確提取數據。即使該數據庫中該日期內有該日期的值,計數結果也始終爲零。 –

+0

結果應該大於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 | 
+---------------------+---------------------------+ 

我們將通過你的情況執行這個查詢

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 | 
+---------------------+ 

查詢應該像選擇1天創建的用戶此

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

您可以使用我使用的變量來嘗試嗎? –

+0

在數據庫中,事務是表,date_paid是事務表內的列之一。我正在使用一個mySQL。 –

+0

@JaeEun對您的案例進行了調整,查看答案。 – mdamia

相關問題