CodeIgniter Forums

Full Version: question about models, ar, and sql strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]CI2RULZ[/eluser]
In the user guide models example, they use the activerecord approach. Do you have to use this method or can you use a simple sql string?, i.e.

$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz FROM exp_pre_email_addresses WHERE foo != 'oof' AND baz != 'zab' ORDER BY foobaz LIMIT 5, 100");

I want to maintain a proper mvc architecture and not simple stick sql strings in the controller (as this is bad practice), however, I'm not interested in the abstraction provided by AR.

If you can use a simple sql string, like above, how does that effect how you would work with or call that class in the controller file?

There are times that the abstraction of activerecord seems to cause more trouble then I see it's worth having, and in porting a project that already has fairly complex query strings, using it without activerecord would help speed the process.

El Forum

[eluser]CroNiX[/eluser]
Sure you can use straight sql queries, but you lose the security and automatic escaping of queries that AR provides so you would have to do them yourself.

You would still have your queries in the model and call them from your controller.

El Forum

[eluser]CI2RULZ[/eluser]
so the ci2 database class / library only sanitizes activerecord methodology?

can you show me an example of the extra work required?

El Forum

[eluser]CroNiX[/eluser]
basically you would have to manually escape any input before saving it like you would any other app. (mysql_escape_string)

$name = $this->db->escape($this->input->post('name'));

$this->db->query("UPDATE `table` set `name` = '$name' WHERE `id` = 4");

If you use AR, CI does this for you on all values being inserted/updated. AR also protects your identifiers automatically by using the backtics (`).

$name = $this->input->post('name');
$this->db->where('id', 4)->update('table', array('name' => $name));