Function name: mysqli_stmt::prepare()
Applicable version: PHP 5, PHP 7
Function Description: This function is used to prepare to execute a preprocessed SQL statement.
Syntax: bool mysqli_stmt::prepare(string $query)
parameter:
Return value: Return true if preparation is successful; otherwise return false.
Example:
// 创建数据库连接$mysqli = new mysqli("localhost", "username", "password", "database"); // 检查连接是否成功if ($mysqli->connect_errno) { echo "连接数据库失败: " . $mysqli->connect_error; exit(); } // 准备预处理语句$query = "INSERT INTO users (name, email) VALUES (?, ?)"; $stmt = $mysqli->prepare($query); if ($stmt) { // 绑定参数$name = "John Doe"; $email = "john@example.com"; $stmt->bind_param("ss", $name, $email); // 执行语句$stmt->execute(); // 检查是否执行成功if ($stmt->affected_rows > 0) { echo "插入成功!"; } else { echo "插入失败!"; } // 关闭语句$stmt->close(); } else { echo "准备语句失败: " . $mysqli->error; } // 关闭数据库连接$mysqli->close();
In the above example, we first create a mysqli
object to connect to the database. Then, we prepare a preprocessing statement using the prepare()
function, which contains two placeholders (?). Next, we use bind_param()
function to bind the values of two parameters. Then, we use the execute()
function to execute the preprocessing statement. Finally, we check the execution results and output the corresponding message. Finally, we closed the preprocessing statement and the database connection.
Note: In actual use, you need to modify the database connection parameters, SQL statements and bound parameter values according to the specific situation.