1

I'm having trouble to convert the below SQL query into CodeIgniter query builder:

$row = $db->prepare("SELECT DATE(message_timestamp) Date, COUNT(DISTINCT messageid) totalCount FROM ic_deliveryreceipts GROUP BY DATE(message_timestamp)");

This is the latest I've tried:

$this->db->select(DATE(message_timestamp) as 'Date', COUNT(DISTINCT messageid) as 'totalCount');
$this->db->group_by(DATE(message_timestamp));
$query = $this->db->get($this->ic_receipts);

but this give a parse error:

syntax error, unexpected 'as' (T_AS), expecting ')'

1
  • This is just a simple matter of not quoting the string parameters in your methods. Commented Sep 13 at 13:16

3 Answers 3

2
$row = $this->db
              ->query("SELECT DATE(message_timestamp) Date, 
                       COUNT(DISTINCT messageid) totalCount 
                       FROM ic_deliveryreceipts 
                       GROUP BY DATE(message_timestamp)")
              ->row();

$row is a stdClass object with two properties: Date, totalCount

echo $row->Date . " " . $row->totalCount;
Sign up to request clarification or add additional context in comments.

Comments

2

I think you need quotes, and also put false on the second (optional) parameter in $this->db->select, as seen in codeigniter docs:

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names. This is useful if you need a compound select statement where automatic escaping of fields may break them.

Try writing like this:

$this->db->select("DATE(message_timestamp) as 'Date', 
                   COUNT(DISTINCT messageid) as 'totalCount'"
                  , FALSE);

$this->db->group_by("DATE(message_timestamp)");

$query = $this->db->get($this->ic_receipts);

Comments

0

My original coding attempt only struggled with wrapping values in quotes.

This is what I finally come up with:

$this->db->select('DATE(message_timestamp) Date, COUNT(DISTINCT messageid) totalCount');
$this->db->from('ic_deliveryreceipts');
$this->db->group_by('DATE(message_timestamp)');
$query = $this->db->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.