Saturday, January 29, 2022

[FIXED] Codeigniter select query with bindings

Issue

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?


Solution

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.



Answered By - Robin Castlin

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.