1

I use Codeigniter as my PHP framework, and in one of my controllers, I want to include a Codeingiter method within a function I created myself. The CodeIgniter method that I want to include in my function is "$this->db->escape($var);", which is an escaping query for Codeigniter. My PHP code is the following:

foreach ($array as $item)
{
  $name = $item["name"];
  $name = processvar($name);
}

function processvar($var) {
  $var = $this->db->escape($var);
  return $var;
}

However, the code above produces the following error message:

Fatal error: Using $this when not in object context in [folder path]/index.php on line #

Please advise how I can include the "$this->db->escape()" method in my own custom function.

0

2 Answers 2

1
function processvar($var) {
    $CI =& get_instance();
    $var = $CI->db->escape($var);

    return $var;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It worked like a charm. I guess I should read CodeIgniter manual more carefully next time.
0

If you want to use a function from another library/framework in your own function, it sometimes it’s best to look at the source code. Remember, modifying the core of any project is inadvisable, but looking at how it works is encouraged in the open source world. It’s really the best way to learn how to code!

Looking at the core of Codeigniter, this function:

$this->db->escape()

Which is located in codeIgniter-base/system/database/DB_driver.php around line 681 is basically a wrapper for:

$this->escape_str()

Which is located in codeIgniter-base/system/database/drivers/sqlsrv/sqlsrv_driver.php around line 258. Which itself is simply this function:

function escape_str($str, $like = FALSE)
{
    // Escape single quotes
    return str_replace("'", "''", $str);
}

So knowing that, why not just do this in your code:

function processvar($var) {
  $var = str_replace("'", "''", $var);
  return $var;
}

That said, is your function going to exist within a Codeigniter project? Then perhaps it’s best to create a new class for your functions that extends the core Codeigniter class but adds your methods (aka: functions) to it. But without knowing the context of this coding on your side, hard to say.

1 Comment

Hi, I appreciate your explanation. However, the function "$this->escape_str()" does much more than just replace single quotes. It escapes double quotes as well and much more. Unfortunately, the function you found in the source code is incomplete.

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.