2015-12-13 105 views
0

我一直試圖從我的表中得到總和。不過,我似乎得到的結果與SQL CodeGo.net,但與CodeIgniter,雖然我確保查詢是相似的。 我沒有得到任何結果,我不知道我到底做錯了什麼。將sql查詢轉換爲php codeigniter

MySQL查詢

SELECT SUM(amount_paid) AS theSum 
FROM invoice 
WHERE MONTH(FROM_UNIXTIME(creation_timestamp)) =10 
AND YEAR(FROM_UNIXTIME(creation_timestamp)) =2015 

我笨查詢

<?php 
    echo $this->db->select('(SELECT SUM(amount_paid) FROM invoice WHERE MONTH (creation_timestamp`) = 10) AS invoice'); 

    $query = $this->db->get('invoice'); 
?> 

,我也試過

<div class="num" data-start="0" data-end=" 
<?php 
    $this->db->select('SUM(amount_paid) as total'); 
    $this->db->where('creation_timestamp', 10); 
    $q=$this->db->get('invoice'); 
    $row=$q->row(); 
    $total=$row->total; 
?>" 

    data-postfix="" data-duration="1500" data-delay="0">0</div> 

    <h3><?php echo $total ;?></h3> 
    <p>Total Payments</p> 
</div> 

我的架構

CREATE TABLE `invoice`(
`invoice_id` int(11) NOT NULL AUTO_INCREMENT, 
`student_id` int(11) NOT NULL, 
`title` longtext COLLATE utf8_unicode_ci NOT NULL, 
`description` longtext COLLATE utf8_unicode_ci NOT NULL, 
`amount` int(11) NOT NULL, 
`amount_paid` longtext COLLATE utf8_unicode_ci NOT NULL, 
`due` longtext COLLATE utf8_unicode_ci NOT NULL, 
`creation_timestamp` int(11) NOT NULL, 
`payment_timestamp` longtext COLLATE utf8_unicode_ci NOT NULL, 
`payment_method` longtext COLLATE utf8_unicode_ci NOT NULL, 
`payment_details` longtext COLLATE utf8_unicode_ci NOT NULL, 
`status` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT 'paid or unpaid', 
PRIMARY KEY (`invoice_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=73 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 
+0

這是http://stackoverflow.com/q/34244773/的轉發,我給你一個鏈接來檢查錯誤。另外,爲什麼MySQL和SQL服務器標籤? –

+0

http://stackoverflow.com/questions/34244773/sum-of-column-by-timestamp-month –

+0

這個主要是關於轉換mysql查詢我剛發佈的其他幫助 – Anasbzr

回答

1

根據您的MySQL查詢,笨活動記錄會工作,

$this->db->select("SUM(amount_paid) AS theSum"); 
$this->db->from("invoice"); 
$this->db->where("MONTH(FROM_UNIXTIME(creation_timestamp)) =10",null, true); 
$this->db->where("YEAR(FROM_UNIXTIME(creation_timestamp)) =2015",null,true); 
$rec = $this->db->get(); 

MySQL的輸出將是:

SELECT SUM(amount_paid) AS theSum 
FROM `invoice` 
WHERE MONTH(FROM_UNIXTIME(creation_timestamp)) = 10 
AND YEAR(FROM_UNIXTIME(creation_timestamp)) = 2015 

或者,您可以directy把你的查詢內部活動記錄如:

$rec = "SELECT SUM(amount_paid) AS theSum 
FROM invoice 
WHERE MONTH(FROM_UNIXTIME(creation_timestamp)) =10 
AND YEAR(FROM_UNIXTIME(creation_timestamp)) =2015"; 

$this->db->query($rec); 
1
$this->db->select_sum("amount_paid", "theSum") 
    ->from("invoice") 
    ->where("MONTH(FROM_UNIXTIME(creation_timestamp))", 10) 
    ->where("YEAR(FROM_UNIXTIME(creation_timestamp))", 2015); 

$rec = $this->db->get(); 
+0

謝謝bilal您的迴應。我已經嘗試過你和nimatullah的例子。但他們似乎沒有工作。是否有可能成爲控制器問題?我的意思是它應該工作。但它根本不顯示結果 – Anasbzr

+0

您可以'echo $ rec'來查看正在構建的查詢。 – Bilal

+0

我如何在模型中獲得$ rec輸出? – Caster