ericbae
ericbae

Reputation: 9644

CodeIgniter - query binding "order by"

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.

Upvotes: 2

Views: 630

Answers (2)

Dino Babu
Dino Babu

Reputation: 5809

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 :) ...

Upvotes: 2

Maulik Vora
Maulik Vora

Reputation: 2584

$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

Upvotes: 1

Related Questions