Function name: mysqli_stmt::bind_param()
Applicable version: PHP 5, PHP 7
Usage: The mysqli_stmt::bind_param() function is used to bind variables to parameters in preprocessing statements. It takes one or more parameters and binds them to placeholders in the specified preprocessing statement.
Syntax: bool mysqli_stmt::bind_param(string $types, mixed &$var1 [, mixed &$... ])
parameter:
$types
: A string that specifies the type of parameter binding. It consists of the following characters:
&$var1 [, &$var2 [, &$... ]]
: One or more reference parameters to specify the variable to bind. The number of variables must match the number of placeholders in $types
.
Return value: Return true on success, and false on failure.
Example:
// 创建预处理语句$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?, ?)"); if ($stmt === false) { die("预处理语句创建失败:" . $mysqli->error); } // 绑定参数$name = "John Doe"; $age = 25; if (!$stmt->bind_param("si", $name, $age)) { die("参数绑定失败:" . $stmt->error); } // 执行预处理语句if (!$stmt->execute()) { die("执行预处理语句失败:" . $stmt->error); } // 关闭预处理语句$stmt->close();
In the example above, we first create a preprocessing statement, and then use bind_param()
function to bind the two variables $name
and $age
to the placeholder in the preprocessing statement ?
. Next, we execute a preprocessing statement that inserts the value of the variable into the database table. Finally, we close the preprocessing statement.
Note that the parameter $types
in bind_param()
function specifies the type of the binding. In this example, we use "si", which means that the first parameter is a string and the second parameter is an integer.