PHP CHAPTER 36

MySQL Prepared

Prepared statements separate SQL instructions from user-supplied values.

📘

What is it?

Prepared statements separate SQL instructions from user-supplied values.

💡

Why do we use it?

They help protect applications against SQL injection and are useful for repeated queries.

⚙️

How does it work?

The SQL is prepared with placeholders, values are bound and the statement is executed.

🧩

Syntax

PHP Syntax
$stmt = $conn->prepare("SELECT * FROM students WHERE email=?");
$stmt->bind_param("s", $email);
💻

Example

PHP Example
<?php

$conn = new mysqli("localhost", "root", "", "aifa_php_lab");

$email = "student@example.com";
$stmt = $conn->prepare("SELECT id,name,email FROM students WHERE email=?");
$stmt->bind_param("s", $email);
$stmt->execute();

$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    echo htmlspecialchars($row['name']);
}

?>
🔍

Example Explained

The ? placeholder is filled safely through bind_param. The result is then fetched.
🚀

More Examples

Use i for integer, s for string, d for double and b for binary data.

⚠️ Important Rules

Prefer prepared statements whenever values originate outside trusted SQL code.

❌ Common Mistakes

Concatenating raw $_GET or $_POST values into SQL.

🌍 Real-World Use

Login, search, filtering and CRUD applications.

📝 Practice Exercise

Create a secure student search using a prepared statement.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →