← Back to Chapters

PHP MySQLi Prepare Function

? PHP MySQLi Prepare Function

? Quick Overview

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.

? Key Concepts

  • Prepared statements use placeholders (?) instead of direct values.
  • Data is bound separately using bind_param().
  • The same statement can be executed multiple times with different values.

? Syntax / Theory

The process of using prepared statements involves four steps: prepare the query, bind parameters, execute the statement, and close resources.

? Code Example

? View Code Example
// 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();

? Live Output / Explanation

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.

? Interactive Concept Flow

  • Prepare → Bind → Execute → Close
  • This flow ensures secure and efficient query execution.

? Use Cases

  • User registration forms
  • Login and authentication systems
  • Secure data insertion, updates, and deletes

✅ Tips & Best Practices

  • Always use prepared statements for user input.
  • Match parameter types correctly (s, i, d, b).
  • Close statements to free server resources.

? Try It Yourself

  • Create a prepared SELECT query using email as input.
  • Insert multiple records using a loop.
  • Update user data securely with prepared statements.