3

how I can replace $this variable in this code? I know that it is incorrect to use $this in functions, but I don't know how I may replace that.

function get_dates($id) {
        $class = $this->db->query("SELECT * FROM schedule WHERE class_id='".$id."'");
        $class = $class->result_array();
        return $class;
    }

PS. I don't won't to work with mysql with standart php features and I strongly believe that it is possible to solve this problem with CI featues.

4
  • 5
    I don't see a $this (BTW: your missing a $ at db) Commented Dec 9, 2014 at 16:39
  • Why aren't you in an object context? Aren't you working with a model? If you use public function get_dates($id) { does it solve your error? The $this is actually correct but your context sounds wrong. By the way, your code is vulnerable to SQL injection. Commented Dec 9, 2014 at 16:46
  • Oops, it seems I forgot to undo. $this->db->query Commented Dec 9, 2014 at 16:46
  • 1
    Are you in a model here? Commented Dec 9, 2014 at 16:47

2 Answers 2

20

If you want to access the CI framework from inside a plain function, you need to get an instance of CI.

function get_dates($id) {
    $ci =& get_instance();

    $class = $ci->db->query("SELECT * FROM schedule WHERE class_id='".$id."'");
    $class = $class->result_array();
    return $class;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@4clover: Note that it is consider best practice to keep the business logic inside models. Although the code Rooneyl wrote is valid, it's better to put queries inside models and methods.
what about CI 4 ?
2

If You are in Helpers or library and want to access the controller object you have to user:

$ci =& get_instance();

Once you will get the controller object you can access any public method or member through $ci reference, you can get the model object as well by setting up a getter method to get the object and then simply reference that object for querying the db.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.