我正在尝试学习如何在 MySQLi 中使用准备好的语句来插入数据.
I am trying to learn how to use prepared statements with MySQLi to insert data.
尽管准备好的语句因其高效重复执行类似语句的能力而受到称赞,但我似乎无法找到使用 MySQLi 在循环中执行多个语句的示例.我特别对以下内容感到困惑:
Even though prepared statements are lauded for their ability to efficiently execute similar statements repeatedly, I can't seem to find examples of executing multiple statements in a loop using MySQLi. I'm especially confused about the following:
bind_param
bind_param
之前还是之后为我的变量赋值bind_param
before my loop or inside my loopbind_param
大多数关于预处理语句的教程都使用 PDO.使用 PDO,可以将一组参数值传递给 execute
,从而无需调用 bindParam
.MySQLi 不是这种情况.
Most tutorials on prepared statements use PDO. With PDO, an array of parameter values can be passed to execute
, eliminating the need to call bindParam
. This is not the case with MySQLi.
PHP 手册 mysqli_prepare
条目有一个示例,显示了以下操作顺序:
The PHP manual mysqli_prepare
entry has an example that shows the following order of operations:
根据上述判断,我假设我需要在循环中调用 bind 语句.
Judging by the above, I had assumed that I would need to call the bind statement within my loop.
然而,PHP 手册 mysqli_stmt_execute
条目有一个显示以下操作顺序的示例:
However, the PHP manual mysqli_stmt_execute
entry has an example that shows the following order of operations:
请注意,此示例未显示的一件事是变量首次声明的位置.我认为将未声明的变量传递给 bind_param
会生成一个通知.我终于发现我可以传递未定义的变量,因为它们是通过引用传递的.
Note that one thing this example doesn't show is where the variables are first declared. I thought passing undeclared variables to bind_param
would generate a notice. I finally figured out that I can pass undefined variables because they are passed by reference.
问题:
一种操作顺序是否优于另一种?还是仅仅取决于你在做什么?两者之间有什么问题吗?
Question:
Is one order of operations preferred over the other? Or does it just depend on what you are doing? Are there any gotchas with one or the other?
注意:代码已经使用 MySQLi,我不想切换到 PDO(现在切换不在本项目范围内).
Note: The code already uses MySQLi and I don't want to switch to PDO (switching now is outside the scope of this project).
因为参数是通过引用传递的,所以可以在之前给变量赋值>或 在调用 bind_param
之后.无论哪种方式都行.
Because the parameters are passed by reference, you can assign the values to the variables before or after the call to bind_param
. Either way will work.
如果变量是通过值传递的,则每次更改它们的值时都需要绑定它们.但是因为它们是通过引用传递的,所以只需要绑定一次即可.
If the variables were passed by value, you would need to bind them each time you changed their value. But since they are passed by reference, you only need to bind them once.
在单次执行的情况下,操作顺序并不重要,可能取决于值的来源.在循环的情况下,你一定要在循环之前调用bind_param
.
In the case of a single execute, the order of operation doesn't really matter and may depend on where the values are coming from. In the case of a loop, you should definitely call bind_param
before the loop.
这篇关于如果在循环中使用 MySQLi 准备好的语句,我什么时候调用 bind_param ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!