Current Location: Home> Latest Articles> How to Correctly Use mysqli to Execute an INSERT Statement? Practical Code Example

How to Correctly Use mysqli to Execute an INSERT Statement? Practical Code Example

gitbox 2025-06-25
<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This section of code is unrelated to the main content, just an example of starting code</span></span><span>]]]

How to Correctly Use mysqli to Execute an INSERT Statement? Practical Code Example

In PHP development, using mysqli to interact with a MySQL database is a common practice. One of the most frequent tasks is executing an INSERT statement to add data into a table. Below is an example showing how to execute an INSERT query with proper syntax and security measures.

2. Writing Secure INSERT Statements - Using Prepared Statements

To prevent SQL injection attacks, it is recommended to use prepared statements.

class = "php">
// Prepare the INSERT statement using placeholders
$<stmt> = $<conn>->prepare("<INSERT INTO users (username, email, age) VALUES (?, ?, ?)>");

// Bind parameters, s for string, i for integer
$<username> = "John Doe";
$<email> = "[email protected]";
$<age> = 28;
$<stmt>->bind_param("ssi", $<username>, $<email>, $<age>);

// Execute the statement
if($<stmt>->execute()) {
    echo "Insert successful, new record ID is: " . $<stmt>->insert_id;
} else {
    echo "Insert failed: " . $<stmt>->error;
}

$<stmt>->close();

3. Closing the Connection

Once the operation is completed, remember to close the database connection.

class = "php">
$<conn>->close();

Summary

  • Use mysqli to connect to the database and ensure the connection is successful.
  • Use prepared statements to prevent SQL injection and enhance security.
  • Check the execution result after executing the query and release resources in time.

By following these steps, you can safely and efficiently use mysqli to execute INSERT statements.