How to Use Prepared Statements in Codeigniter

How can I Use Prepared Statements in CodeIgniter

CodeIgniter does not support Prepared Statements. If you look at the sourcecode for CI's Database class, you will see that they resolve bindings simply by replacing the question marks with the data from the passed array:

  • https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_driver.php#L874

They only support Query Binding with unnamed placeholders. See http://ellislab.com/codeigniter/user-guide/database/queries.html

Query Bindings

Bindings enable you to simplify your query syntax by letting the system put the queries together for you. Consider the following example:

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));

The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.

and http://ellislab.com/forums/viewthread/105112/#528915

Even though CI doesn’t support prepared statements, it does support Query Bindings. With prepared statements you have to call some type of prepare() function and then some type of execute() function. With query bindings, you only have to call one function and it basically does the same thing. Because of this, I like query bindings better than prepared statements.

On a sidenote, changing ? to :foo is merely changing from unnamed to named bindings (which CI apparently does not support either). Just because you use either or doesn't mean you are preparing the statements.

Codeigniter DB class vs prepared statements

CI doesn’t support prepared statements, it does support Query Bindings though. Both query bindings and prepared statements prevent sql injection. But I prefers AR because the ease of use. Also it makes the query more readable.

You can check this link for more details.

And check the CI Query Binding from this link

CodeIgniter Call to undefined method prepare

Since CodeIgniter does not support prepared statements, you could modify your code like this to use the PDO object to run your prepared statements :

public function edit_done() {
$name = $this->input->post("name");
$id = $this->input->post("id");

$query = $this->db->conn_id->prepare('update alimente set name = ? where id = ?');
$query->execute($name, $id);

redirect("alimente");


Related Topics



Leave a reply



Submit