5

I am using Codeigniter to fire a query on my db. The code looks like:

$this->db->select("category.Name,
booking.Comment,
CASE WHEN amount > 0 THEN amount END AS PosAmount,
CASE WHEN amount < 0 THEN amount END AS NegAmount");

But I always get an

You have an error in your SQL syntax ... right syntax to use near
'WHEN amount > 0 THEN amount END AS PosAmount, `CASE` WHEN amount < 0 
THEN amount' at line 1

Codeigniter is escaping the CASE but I do not know how to prevent this.

Any ideas?

3
  • $query=$this->db->query("category.Name, booking.Comment, CASE WHEN amount > 0 THEN amount END AS PosAmount, CASE WHEN amount < 0 THEN amount END AS NegAmount"); $query->result(); Commented Feb 19, 2016 at 9:13
  • That is just adding the String to the actual query? Commented Feb 19, 2016 at 9:16
  • This question is similar to: How to write a SELECT clause containing an SQL function call with CodeIgniter's select() method. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jun 4 at 17:48

1 Answer 1

8

From the documentation :

$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.

In your case :

$this->db->select("category.Name,
booking.Comment,
CASE WHEN amount > 0 THEN amount END AS PosAmount,
CASE WHEN amount < 0 THEN amount END AS NegAmount", FALSE);

This second parameter can also be used in where and join clauses.

Sign up to request clarification or add additional context in comments.

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.