The mysqli_stmt_execute()
function in PHP is used to execute a prepared statement that was previously created using mysqli_prepare()
. This is a part of the MySQLi (MySQL Improved) extension and helps in executing SQL queries securely — especially useful for preventing SQL injection.
🔧 Syntax
mysqli_stmt_execute(mysqli_stmt $statement): bool
- $statement: The prepared statement object returned by
mysqli_prepare()
. - Returns:
true
on success,false
on failure.
✅ Basic Usage Example – INSERT Statement
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare the statement
$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
// Bind parameters
$name = "John Doe";
$email = "john@example.com";
$stmt->bind_param("ss", $name, $email); // "ss" means two string parameters
// Execute the statement
if ($stmt->execute()) {
echo "New record inserted successfully!";
} else {
echo "Error: " . $stmt->error;
}
// Close statement and connection
$stmt->close();
$mysqli->close();
?>
🕵️♂️ SELECT Statement Example
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE email = ?");
$email = "john@example.com";
$stmt->bind_param("s", $email);
$stmt->execute();
// Bind result variables
$stmt->bind_result($id, $name);
// Fetch values
while ($stmt->fetch()) {
echo "ID: $id, Name: $name<br>";
}
$stmt->close();
$mysqli->close();
?>
🧠 Why Use mysqli_stmt_execute()
?
- Prevents SQL injection by separating SQL logic from data.
- Safer and cleaner way to execute queries.
- Useful when executing the same query multiple times with different data.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.