PHP mysqli::stmt_init() / mysqli_stmt_init() 函数分配并初始化与 mysqli_stmt_prepare 一起使用的语句对象()。
注意:在调用 mysqli_stmt_prepare() 之前,对任何 mysqli_stmt 函数的任何后续调用都将失败。
语法
//面向对象风格
public mysqli::stmt_init()
//面向过程风格
mysqli_stmt_init(mysql)
参数
mysql | 必填。 仅适用于面向过程风格:指定 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。 |
返回值
返回一个对象。
示例:面向对象风格
下面的示例显示了mysqli::stmt_init()方法的用法。
<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: ". $mysqli->connect_error;
exit();
}
//创建准备好的语句
$stmt = $mysqli->stmt_init();
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
$stmt->prepare($query);
//绑定参数
$stmt->bind_param('ssd', $name, $city, $salary);
//设置参数并执行
$name = "John";
$city = "London";
$salary = 2800;
$stmt->execute();
$name = "Marry";
$city = "Paris";
$salary = 2850;
$stmt->execute();
echo "Records inserted successfully.";
//关闭连接
$mysqli->close();
?>
上述代码的输出将类似于:
Records inserted successfully.
示例:面向过程风格
下面的示例显示mysqli_stmt_init的用法() 函数。
<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ". mysqli_connect_error();
exit();
}
//创建准备好的语句
$stmt = mysqli_stmt_init($mysqli);
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
//绑定参数
mysqli_stmt_bind_param($stmt, 'ssd', $name, $city, $salary);
//设置参数并执行
$name = "John";
$city = "London";
$salary = 2800;
mysqli_stmt_execute($stmt);
$name = "Marry";
$city = "Paris";
$salary = 2850;
mysqli_stmt_execute($stmt);
echo "Records inserted successfully.";
//关闭连接
mysqli_close($mysqli);
?>
上述代码的输出将类似于:
Records inserted successfully.