<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>]]]
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.
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();
Once the operation is completed, remember to close the database connection.
class = "php">
$<conn>->close();
By following these steps, you can safely and efficiently use mysqli to execute INSERT statements.
Related Tags:
mysqli