Search code examples
codeigniter-4

How to use the build in CRUD-Modell for insert and escape the datas on Codeigniter4


I tried to understand the new ways and possibilities with Codeigniter4.

I see a shorter way by the build in Crud-Model to do the simplest job with a bit less of code.

Do I insert new datas in the controller with this code, after I setup the myModel with the protected variables.?

$this->myModel->insert(['filed1' => 'value1,
                    'field2'  =>$this->request->getPost('field')...
                ]));

So that works fine.

Now I want to make it a bit more secure and I want to insert only escaped values.

For that CodeIgniter has a lot of built-in functions/helpers. So I try to use "escape()" in this way

 $this->myModel->insert(escape(['filed1' => 'value1,
                        'field2'  =>$this->request->getPost('field')...
                    ])));

but it failed with the error "Call to undefined function App\Controllers\escape()"

So how I can insert only escaped values into my db with the nicest/fastest code/Way may which is supported with the build-in basic Crud functions?

Thanks to teach/help me in this point!


Solution

  • escape doesn't work in a global context because that method is a member of the Database class (or rather, a parent class that implements the ConnectionInterface interface).

    esc is a global function, which is why that works in a global context.

    However, esc is designed to escape data that's going into web pages, not databases.

    The good news is, if you're using Query Builder methods, then input is already escaped for you automatically:

    It also allows for safer queries, since the values are escaped automatically by the system.

    If for some reason you still need to manually escape input (e.g. using basic queries), there are a few options, including the escape method you were trying to use earlier.