tthlaszlo
tthlaszlo

Reputation: 485

Codeigniter select query with bindings

I have a big problem, what i can't solve. In codeigniter i created a model, who done this:

public function listazas($mettol, $mennyit, $feltetel)
    {
        $query = "SELECT * FROM vicc ORDER BY ? DESC LIMIT ?,?";
        $query = $this->db->query($query, array($feltetel, $mettol, $mennyit));

        return $query->result_array();
    }

In the controller i use it:

   $viccek = $this->index_model->listazas(0, 10, "ertekeles");

   $this->load->view('index/index', array(
       'viccek' => $viccek
   ));

And here the sql don't do the order by section... why?

Upvotes: 1

Views: 10871

Answers (3)

ramkalyan
ramkalyan

Reputation: 11

$sql = "INSERT INTO tbl_user (name, age, groupname)
        VALUES (?, ?, ?)";
$this-> db-> query($sql,array('codeigniter', 35, 'Group 1'));

Upvotes: 1

Sinte
Sinte

Reputation: 91

its so easy have a look at this example just the model only in the controller you just have to call the method with these parameters for more detail solution you can ask me

public function read_all($limit,$start){
    $this->db->select('*');        
    $this->db->from('postes');
    $this->db->order_by('id', 'ASC');
    $this->db->limit($limit, $start);    
    $q = $this->db->get();
    return $q->result_array();
}

Upvotes: 0

Robin Castlin
Robin Castlin

Reputation: 10996

Well it's because you're doing a ORDER BY 'column' instead of ORDER BY column.

You'll have to do a replace on current function with:

public function listazas($mettol, $mennyit, $feltetel)
{
    $feltetel = $this->db->escape_like_str($feltetel);
    $query = "SELECT * FROM vicc ORDER BY {$feltetel} DESC LIMIT ?,?";
    $query = $this->db->query($query, array($mettol, $mennyit));

    return $query->result_array();
}

Basicly your query() escaped the $feltetel with '' around it, making it act like a string instead of a column name.

For a query as simple as this one, you can do it easier through Active Records.

You could also try to troubleshoot this yourself by running a echo $this->db->last_query(); after the $this->db->query() and compare the result.
Then you would had noticed the '' after ORDER BY.

Upvotes: 4

Related Questions