The mysqli_prepare()
function in PHP is used to prepare an SQL statement for execution. It’s part of the MySQLi (MySQL Improved) extension and is commonly used to prevent SQL injection, especially when working with user input.
🔹 Syntax:
mysqli_prepare(mysqli $link, string $query): mysqli_stmt|false
- $link: The MySQLi connection object.
- $query: The SQL query string with placeholders (
?
) for parameters. - Returns a
mysqli_stmt
object on success orfalse
on failure.
🔹 Why Use mysqli_prepare()
?
- It separates the query structure from the data.
- Helps avoid SQL injection attacks.
- Required for using bound parameters (
?
).
🔹 Basic Example (SELECT)
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
// Prepare the SQL statement
$stmt = mysqli_prepare($mysqli, "SELECT name, email FROM users WHERE id = ?");
// Bind parameters (i = integer)
mysqli_stmt_bind_param($stmt, "i", $userId);
$userId = 1;
// Execute the prepared statement
mysqli_stmt_execute($stmt);
// Bind result variables
mysqli_stmt_bind_result($stmt, $name, $email);
// Fetch the results
while (mysqli_stmt_fetch($stmt)) {
echo "Name: $name, Email: $email\n";
}
// Close the statement and connection
mysqli_stmt_close($stmt);
$mysqli->close();
?>
🔹 Example (INSERT)
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = mysqli_prepare($mysqli, "INSERT INTO users (name, email) VALUES (?, ?)");
// Bind parameters (s = string)
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
$name = "John Doe";
$email = "john@example.com";
mysqli_stmt_execute($stmt);
echo "Inserted ID: " . mysqli_insert_id($mysqli);
mysqli_stmt_close($stmt);
$mysqli->close();
?>
🔹 Parameter Types
"i"
= integer"d"
= double"s"
= string"b"
= blob
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.