PHP mysqli stmt_init() 函数
定义和用法
stmt_init()
/ mysqli_stmt_init()
函数初始化语句并返回适合 mysqli_stmt_prepare()
使用的对象。
实例
例子 1 - 面向对象风格
初始化一个语句并返回一个用于 stmt_prepare()
的对象:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$city="Sandnes";
// 创建一个预处理语句
$stmt = $mysqli -> stmt_init();
if ($stmt -> prepare("SELECT District FROM City WHERE Name=?")) {
// 绑定参数
$stmt -> bind_param("s", $city);
// 执行查询
$stmt -> execute();
// 绑定结果变量
$stmt -> bind_result($district);
// 获取值
$stmt -> fetch();
printf("%s is in district %s", $city, $district);
// 关闭语句
$stmt -> close();
}
$mysqli -> close();
?>
例子 2 - 过程式风格
初始化一个语句并返回一个用于 mysqli_stmt_prepare() 的对象:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$city="Sandnes";
// 创建一个预处理语句
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?")) {
// 绑定参数
mysqli_stmt_bind_param($stmt, "s", $city);
// 执行查询
mysqli_stmt_execute($stmt);
// 绑定结果变量
mysqli_stmt_bind_result($stmt, $district);
// 获取值
mysqli_stmt_fetch($stmt);
printf("%s is in district %s", $city, $district);
// 关闭语句
mysqli_stmt_close($stmt);
}
mysqli_close($con);
?>
语法
面向对象风格:
$mysqli -> stmt_init()
过程式风格:
mysqli_stmt_init(connection)
参数 | 描述 |
---|---|
connection | 必需。指定要使用的 MySQL 连接。 |
技术细节
返回值: | 返回对象。 |
---|---|
PHP 版本: | 5+ |