問題描述
我正在嘗試學習如何在 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
之前還是之后為我的變量賦值
- 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
大多數關于預處理語句的教程都使用 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 ?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!