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).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…