PHP mysqli prepare() 函数
示例 - 面向对象的样式
准备要执行的 SQL 语句:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// prepare and bind
$stmt = $mysqli -> prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt -> bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt -> execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt -> execute();
echo "New records created successfully";
$stmt -> close();
$mysqli -> close();
?>
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// prepare and bind
$stmt = $mysqli -> prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt -> bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt -> execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt -> execute();
echo "New records created successfully";
$stmt -> close();
$mysqli -> close();
?>
定义和用法
prepare() / mysqli_prepare() 函数用于准备一条SQL语句以供执行。
语法
面向对象的风格:
$mysqli -> prepare(query)
程序风格:
mysqli_prepare(connection, query)
参数值
参数 | 描述 |
---|---|
connection | 必需。规定要使用的 MySQL 连接。 |
query | 必需。指定 SQL 查询。 注释:不要在查询末尾添加分号! |
技术细节
返回值: | 成功的声明对象。 失败时为 FALSE |
---|---|
PHP 版本: | 5+ |