1

Just getting started with parameter binding and I've read all through the docs and quite a few questions/answers here, but I can't seem to get this to work.

Simply sorting via get request.

public function getAttributeGroups($data = array()) {
    $params = array();
    $sql = "
        SELECT * 
        FROM {$this->db->prefix}attribute_group ag 
        LEFT JOIN {$this->db->prefix}attribute_group_description agd 
        ON (ag.attribute_group_id = agd.attribute_group_id) 
        WHERE agd.language_id = '" . (int)$this->config->get('config_language_id') . "'";

    $sort_data = array(
        'agd.name',
        'ag.sort_order'
    );  

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
        //$sql .= " ORDER BY " . $data['sort'];
        $sql .= " ORDER BY :sort";
        $params[':sort'] = $data['sort'];
    } else {
        $sql .= " ORDER BY agd.name";   
    }   

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
        $sql .= " DESC";
    } else {
        $sql .= " ASC";
    }

    if (isset($data['start']) || isset($data['limit'])) {
        if ($data['start'] < 0) {
            $data['start'] = 0;
        }               

        if ($data['limit'] < 1) {
            $data['limit'] = 20;
        }   

        $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    }

    $query = $this->db->query($sql, $params);

    return $query->rows;
}

The quoted line is the original that sorts just fine, but in analyzing the code is open to injections.

The above does execute a query and returns data, but it doesn't sort by the passed in binding.

What am I missing?

TylerH
  • 20,799
  • 66
  • 75
  • 101
secondman
  • 3,233
  • 6
  • 43
  • 66
  • Simply, you can't do it that way. You cannot bind a column or table name as a parameter. You'll need to check the input `$data['sort']` against an array of acceptable column names with `in_array()` to prevent injection there. – Michael Berkowski Dec 29 '14 at 18:08
  • ^^ And once you have validated it, use the variable in the query `ORDER BY {$data['sort']}` I know your instinct is to try to use a parameter, but it isn't supported in that way. Array validation prevents injection though. http://stackoverflow.com/a/16305689/541091 – Michael Berkowski Dec 29 '14 at 18:10
  • Beautiful. Thank you Michael. The heredoc formatting of the variable resolved the injection errors I was getting. I appreciate your time. – secondman Dec 29 '14 at 18:43

0 Answers0