问题
I am trying to learn how to use prepared statements with MySQLi to insert data.
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:
- whether to call
bind_param
before my loop or inside my loop - whether to assign values to my variables before or after the call to
bind_param
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.
The PHP manual mysqli_prepare entry has an example that shows the following order of operations:
- assign values to variables
- prepare statement
- bind variables
- execute
- close
Judging by the above, I had assumed that I would need to call the bind statement within my loop.
However, the PHP manual mysqli_stmt_execute entry has an example that shows the following order of operations:
- prepare statement
- bind variables
- assign values to variables
- execute
- assign values to variables
- execute
- close
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?
Note: The code already uses MySQLi and I don't want to switch to PDO (switching now is outside the scope of this project).
回答1:
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.
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.
来源:https://stackoverflow.com/questions/13845113/when-do-i-call-bind-param-if-using-mysqli-prepared-statements-in-a-loop