The prepare() function in MySQLi is used to create prepared statements. Prepared statements separate SQL logic from data, making database operations safer, faster, and resistant to SQL injection attacks.
The process of using prepared statements involves four steps: prepare the query, bind parameters, execute the statement, and close resources.
// Create database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare SQL statement with placeholders
$stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email) VALUES (?, ?, ?)");
// Bind parameters to the statement
$first_name = "John";
$last_name = "Doe";
$email = "john.doe@example.com";
$stmt->bind_param("sss", $first_name, $last_name, $email);
// Execute prepared statement
if ($stmt->execute()) {
echo "Record inserted successfully. ID: " . $stmt->insert_id;
} else {
echo "Error: " . $stmt->error;
}
// Close statement and connection
$stmt->close();
$conn->close();
If the execution is successful, a new record is inserted into the database and the auto-generated ID is displayed. If an error occurs, the error message explains what went wrong.