2

In my CodeIgniter, I'm binding my query to a set of variables.

$q = "SELECT * FROM my_table WHERE name=? ORDER BY ?"; $name = $this->input->get("name"); $order_by = $this->input->get("order_by"); $this->db->query($q, array($name, $order_by)); 

But "order_by" isn't working properly. I've searched through, but I'm not sure how to "sanitize" the "order by" clause.

2 Answers 2

2

try this way,

$order_by_arr = array('name', 'age', 'date'); if (!in_array($order_by, $order_by_arr)) { $order_by = 'name'; } // now u can use $order_by. its safe :) ... 
Sign up to request clarification or add additional context in comments.

4 Comments

Hm. Makes sense, but seems kind of hacky!
shouldn't it be if(in_array) instead of if(!in_array)?
yea. its up to u. i just said an idea. :)
just tried it and does work wonderfully. :) love to hear more thoughts from others too.
1
$order_by = $this->db->escape_like_str($this->input->get("order_by")); $q = "SELECT * FROM my_table WHERE name=? ORDER BY {$order_by}"; $name = $this->input->get("name"); $this->db->query($q, array($name)); 

refer this link, this suits your requirement best.

Query Binding in codeigniter

3 Comments

That does not sanitize the value of $order_by - does not prevent SQL injection on the order_by variable.
I run the above query via URL as follows - myapp/get_table?name=table_name&order_by=id - now, I can do a following SQL injection myapp/get_table?name=table_name&order_by=id;select * from users - and the injected query will return results - so I don't think it's secure.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.