如何在 CodeIgniter 中使用准备好的语句 [英] How can I Use Prepared Statements in CodeIgniter

查看:33
本文介绍了如何在 CodeIgniter 中使用准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我需要在我的网站中使用准备好的语句.我试过用这个

Hi all I need to use Prepared Statements in my site. I tried use this

$sql = "SELECT * FROM tbl_user WHERE uid=:id and activation_key=:key";
$query = $this->db->query( 
    $sql, 
    array( ':id' => $uid ,':key' => $activation_key)
);

但这不起作用.当我将 :id:key 更改为 ? 时,它的工作原理.

but this is not working. When I change :id and :key to ? its working.

推荐答案

CodeIgniter 不支持 Prepared Statements.如果您查看 CI 的 Database 类的源代码,您将看到它们通过用传递的数组中的数据替换问号来解析绑定:

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:

它们仅支持带有未命名占位符的查询绑定.请参阅 http://ellislab.com/codeigniter/user-guide/database/queries.html

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

查询绑定

绑定使您可以通过让系统为您将查询放在一起来简化查询语法.考虑以下示例:

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.

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

尽管 CI 不支持准备好的语句,但它确实支持查询绑定.对于准备好的语句,您必须调用某种类型的 prepare() 函数,然后调用某种类型的 execute() 函数.使用查询绑定,您只需调用一个函数,它基本上做同样的事情.因此,与准备好的语句相比,我更喜欢查询绑定.

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.

顺便说一句,将 ? 更改为 :foo 只是从未命名绑定更改为命名绑定(CI 显然也不支持).仅仅因为您使用 或 并不意味着您正在准备语句.

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 中使用准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆