bg_image
header

Prepared Statements

A Prepared Statement is a programming technique, especially used when working with databases, to make SQL queries more secure and efficient.

1. How does a Prepared Statement work?

It consists of two steps:

  1. Prepare the SQL query with placeholders
    Example in SQL:

SELECT * FROM users WHERE username = ? AND password = ?

 

 

  • (Some languages use :username or other types of placeholders.)

  • Bind parameters and execute
    The real values are bound later, for example:

 

$stmt->bind_param("ss", $username, $password);
$stmt->execute();

2. Advantages

Protection against SQL injection:
User input is treated separately and safely, not directly inserted into the SQL string.

Faster with repeated use:
The SQL query is parsed once by the database server and can be executed multiple times efficiently (e.g., in loops).


3. Example in PHP using MySQLi

$conn = new mysqli("localhost", "user", "pass", "database");
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email); // "s" stands for string
$email = "example@example.com";
$stmt->execute();
$result = $stmt->get_result();

In short:

A Prepared Statement separates SQL logic from user input, making it a secure (SQL Injection) and recommended practice when dealing with databases.


Random Tech

Subversion - SVN


Apache_Subversion_logo.svg.png