将sql查询转换为php codeigniter

时间:2015-12-13 04:34:21

标签: php mysql codeigniter

我一直试图从我的桌子上得到一笔钱。但是,我似乎得到sql的结果,但不是CodeIgniter,虽然我确保查询是相似的。 我没有得到任何结果,我也不知道我到底做错了什么。

MySql查询

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

我的CodeIgniter查询

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

2 个答案:

答案 0 :(得分:1)

根据您的MySQL查询,codeIgniter活动记录将起作用,

$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

或者,您可以直接将查询放在活动记录中,如:

$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 :(得分: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();