2016-06-10 86 views
0

我正在開發一個系統,應該輸出一天內發送的短信總數。它也應該分開交付的和失敗的。 它只應該把當天的記錄放在一起......只有當天的記錄。 我的數據庫是smsdb。PHP Mysql select語句顯示當天僅記錄

$sql = "CREATE TABLE smsdb (
    id INT(6) AUTO_INCREMENT PRIMARY KEY, 
    sms_text VARCHAR(300) NOT NULL, 
    receiver_number VARCHAR(30) NOT NULL, 
    time_sent DATETIME, 
    status VARCHAR(20))"; 


//I tried to use the command to display todays records but I get all records even for other days. 

$sql = ("SELECT DATE(time_sent) AS date, COUNT(*) as total_sent, SUM(status = 'Success') as delivered,SUM(status = 'failed') AS failed FROM smsdb GROUP BY DATE(time_sent) "); 

我只希望在這一天的總記錄。 請幫助我

+0

您所查詢的引用表中不存在的狀態列。你能否用正確的表格定義更新你的問題? – chocochaos

+0

有沒有條件 –

+0

什麼類型的字段time_sent是? –

回答

1

在哪裏標準只是篩選當前日期:

SELECT 
    DATE(time_sent) AS date, 
    COUNT(*) as total_sent, 
    SUM(case when status = 'Success' then 1 else 0 end) as delivered, 
    SUM(case when status = 'failed' then 1 else 0 end) AS failed 
FROM smsdb 
WHERE date(time_sent)=curdate() 
GROUP BY DATE(time_sent) 
1

您未投入日期過濾器。您可以在把它作爲一個變量,所以你可以選擇其他日子:

$sql = ("SELECT DATE(time_sent) AS date, COUNT(*) as total_sent, SUM(status = 'Success') as delivered,SUM(status = 'failed') AS failed FROM smsdb WHERE DATE(time_sent) = '$date_selected'"); 

請注意,您真的應該綁定參數這一點,但是這會給你一個想法。

另一種選擇,如果你總是希望它是當前日期是使用CURDATE()功能:

$sql = ("SELECT DATE(time_sent) AS date, COUNT(*) as total_sent, SUM(status = 'Success') as delivered,SUM(status = 'failed') AS failed FROM smsdb WHERE DATE(time_sent) = CURDATE()");