Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

php - When do I call bind_param if using MySQLi prepared statements in a loop?

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:

  1. assign values to variables
  2. prepare statement
  3. bind variables
  4. execute
  5. 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:

  1. prepare statement
  2. bind variables
  3. assign values to variables
  4. execute
  5. assign values to variables
  6. execute
  7. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...