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:
bind_param
before my loop or inside my loopbind_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:
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:
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With