Current Location: Home> Latest Articles> How to call execute() after using stmt_init

How to call execute() after using stmt_init

M66 2025-05-29

When using PHP to operate MySQL databases, the mysqli extension provides rich preprocessing statements (Prepared Statements) support, which can effectively prevent SQL injection attacks and improve the security and efficiency of database operations. This article will focus on how to initialize a statement object using the mysqli::stmt_init method and execute SQL statements through the object.

1. What is mysqli::stmt_init ?

mysqli::stmt_init() is a method of the mysqli class that is used to initialize an empty statement object ( mysqli_stmt ). This object can be bound to SQL query statements by calling prepare() method and further called bind_param() , execute() and other methods for operation.

The basic syntax is as follows:

 $stmt = $mysqli->stmt_init();

where $mysqli is a mysqli object that has been connected to the database.

2. Complete example: Use stmt_init to execute a SQL query

Here is a complete PHP example using stmt_init initialization statement and executing SQL queries:

 <?php
// Database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check the connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Initialize statement object
$stmt = $mysqli->stmt_init();

// Preprocessing SQL Statement
if ($stmt->prepare("SELECT name, email FROM users WHERE id = ?")) {
    // Bind parameters
    $id = 1;
    $stmt->bind_param("i", $id);

    // 执行Statement
    $stmt->execute();

    // Binding result variables
    $stmt->bind_result($name, $email);

    // Get query results
    while ($stmt->fetch()) {
        echo "Username: $name, Mail: $email<br>";
    }

    // 关闭Statement
    $stmt->close();
} else {
    echo "SQL Preprocessing失败: " . $stmt->error;
}

// Close the connection
$mysqli->close();
?>

3. Things to note

  • After calling stmt_init() , you must use the prepare() method to actually bind the SQL statement.

  • The type parameters in bind_param(), for example, "i" represents an integer, and "s" represents a string, must be set correctly.

  • Be sure to call $stmt->close() after using the statement object to free up the resource.

4. Why use stmt_init instead of directly $mysqli->prepare() ?

Although you can directly use $mysqli->prepare() for statement preparation, stmt_init() provides more detailed control, such as more useful when you need to check whether the statement is reusable or use a low-level interface.

5. Examples of practical application scenarios