MySQL Prepared Statements

PHP MySQL Prepared Statements

Prepared statements are an absolutely critical feature in PHP that help make your databases more secure and faster to execute.

They are primarily used to prevent SQL Injection—a malicious technique where hackers attempt to interfere with your database queries by typing code into your website's input forms.


How Prepared Statements Work

Instead of mixing user data directly into your SQL string, you send a "template" to the database first, and then send the data parameters later.

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled with ?).
  2. Compile: The database parses, compiles, and optimizes the template.
  3. Execute: The application binds the values to the parameters, and the database executes the statement.

Because the data is sent separately from the query logic, it is impossible for malicious input to alter the structure of the query!

Prepared Statements Example

<?php
$servername = "localhost";
$username = "root";
$password = "your_password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// 1. PREPARE the statement (Notice the '?' marks) $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");

// 2. BIND the parameters (The "sss" means we are binding 3 strings) $stmt->bind_param("sss", $firstname, $lastname, $email);

// 3. EXECUTE $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute();

$firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); // Execute again with new data!

echo "New records created securely!";

$stmt->close(); $conn->close(); ?>

Using prepared statements is an industry-standard best practice!