带有准备好的语句的可变参数/结果绑定 [英] Variable parameter/result binding with prepared statements

查看:47
本文介绍了带有准备好的语句的可变参数/结果绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我即将结束的一个项目中,我为 PHP 编写并实现了一个对象关系映射解决方案.在怀疑者和梦想家大喊这到底是怎么回事?"之前,放松一下——我还没有找到让后期静态绑定工作的方法——我只是尽我所能地解决它.

无论如何,我目前没有使用准备好的语句进行查询,因为我无法想出一种方法将可变数量的参数传递给 bind_params()bind_result() 方法.

你问为什么我需要支持可变数量的参数?因为我的模型的超类(把我的解决方案想象成一个被修改的 PHP ActiveRecord 想要的)是定义查询的地方,所以 find() 方法,例如,不知道它需要绑定多少参数.

现在,我已经考虑过构建一个参数列表并将一个字符串传递给 eval(),但我不太喜欢这个解决方案——我宁愿只是实现我自己的安全检查并传递语句.

有人对如何完成这项工作有任何建议(或成功案例)吗?如果您能帮我解决第一个问题,也许我们可以解决绑定结果集的问题(我怀疑这会更困难,或者如果涉及确定表结构的初始查询,至少会占用更多资源).

解决方案

在 PHP 中,您可以使用 call_user_func_array.一个方法的例子是:

call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);

将调用该函数,并将数组中的每个成员作为其自己的参数传递.

In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.

Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the bind_params() or bind_result() methods.

Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.

Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.

Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).

解决方案

In PHP you can pass a variable number of arguments to a function or method by using call_user_func_array. An example for a method would be:

call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);

The function will be called with each member in the array passed as its own argument.

这篇关于带有准备好的语句的可变参数/结果绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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