garethdn
garethdn

Reputation: 12351

Passing data from controller to model

I'm having trouble passing data from my controller to my model using Codeigniter. I'm getting an Internal Server Error on the browser console but have narrowed it down to the issue outlined above.

Here is my code:

Controller

public function get_results() {
        $numOfDraws = $this->input->post('numOfDraws');
        $data = $this->lotto_model->get_results($numOfDraws);
        echo json_encode($data);
    }

Model

  public function get_results($numOfDraws)
        {
            $query = $this->db->query('SELECT * FROM lotto ORDER BY id DESC LIMIT "$numOfDraws"');
            return $query->result();
        }

If i hardcode the LIMIT the query works successfully. I know that $numOfDraws is equal to the correct value in the controller.

Can anyone advise?

Upvotes: 1

Views: 120

Answers (3)

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

Try this--

        $query = $this->db->query("SELECT * FROM lotto ORDER BY id DESC LIMIT $numOfDraws");
        return $query->result();

Upvotes: 1

No Results Found
No Results Found

Reputation: 102735

Your query is single quoted so it won't parse variables, your generated SQL would literally be:

SELECT * FROM lotto ORDER BY id DESC LIMIT "$numOfDraws"

Just use CI's "ActiveRecord" class if you want cleaner syntax, abstraction, and better security:

public function get_results($numOfDraws)
{
    return $this->db
        ->limit($numOfDraws)
        ->order_by('id', 'DESC')
        ->get('lotto')
        ->result();
}

Or one way to fix your original query:

$query = $this->db
    ->query('SELECT * FROM lotto ORDER BY id DESC LIMIT '.(int) $numOfDraws);

Upvotes: 3

Mischa
Mischa

Reputation: 43298

First of all variable injection into a string only works with double quotes, not with single quotes. Secondly your current code is open to SQL injection.

CodeIgniter provides functionality to prevent this:

$query = $this->db->query('SELECT * FROM lotto ORDER BY id DESC LIMIT ?', array($numOfDraws));

Upvotes: 4

Related Questions