MySQL Prepared

sa sahaya jerish Updated 20 Oct 2026
6 min read ·Lesson 151 of 155
In this post

What Is a Prepared Statement? In simple terms: A prepared statement is an SQL query with blanks ( ? ) where the values go. You send the query to MySQL first, and the values separately. MySQL treats th

What Is a Prepared Statement?

In simple terms: A prepared statement is an SQL query with blanks (?) where the values go. You send the query to MySQL first, and the values separately. MySQL treats the values strictly as data — never as part of the SQL command — so no input, however strange or malicious, can change what the query does.

Technically: With prepared statements, MySQL parses and plans the SQL template once (prepare), then executes it with bound parameters (execute), possibly many times. Because SQL code and data travel separately, prepared statements are the primary defense against SQL injection. MySQLi supports them through mysqli::prepare() and the mysqli_stmt class, plus the shortcuts mysqli_stmt::execute(array) (PHP 8.1+) and mysqli::execute_query() (PHP 8.2+).


The Problem: SQL Injection

<?php
$email = "x' OR '1'='1";   // submitted through a login or search form

$unsafeSql = "SELECT id, name FROM customers WHERE email = '$email'";
echo $unsafeSql . "\n";

 

Output

SELECT id, name FROM customers WHERE email = 'x' OR '1'='1'

 

The input closed the string with ' and added OR '1'='1', a condition that is always true. Executed, this query would return every customer. Similar tricks can bypass logins, read other tables, or delete data.

The Same Lookup With a Prepared Statement

<?php
require __DIR__ . '/src/db.php';

$email = "x' OR '1'='1";

$result = db()->execute_query('SELECT id, name FROM customers WHERE email = ?', [$email]);

echo "Matching customers: " . $result->num_rows . "\n";

 

Output

Matching customers: 0

 

MySQL searched for a customer whose email is literally x' OR '1'='1 — and found none. The quotes inside the value have no special meaning.


The Prepared Statement Lifecycle

1. prepare  ──►  SELECT name, price, stock FROM products WHERE sku = ?   (parsed once)
2. bind     ──►  ? = 'PEN-01'
3. execute  ──►  MySQL runs the plan with the value
4. fetch    ──►  read the result rows
   (repeat 2–4 with other values)

 

Step by Step With bind_param()

<?php
require __DIR__ . '/src/db.php';

$db = db();

$stmt = $db->prepare('SELECT name, price, stock FROM products WHERE sku = ?');
$stmt->bind_param('s', $sku);

foreach (['PEN-01', 'LAMP-01', 'NOPE-99'] as $sku) {
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc();

    echo $product === null
        ? "$sku: not found\n"
        : "$sku: {$product['name']}, ₹{$product['price']}, {$product['stock']} in stock\n";
}

$stmt->close();

 

Output

PEN-01: Gel Pen, ₹20.00, 120 in stock
LAMP-01: Desk Lamp, ₹1299.00, 8 in stock
NOPE-99: not found

 

How It Works

  1. prepare() sends the template with one ? placeholder. MySQL parses it and returns a statement object.
  2. bind_param('s', $sku) binds the variable $sku (by reference) as a string parameter.
  3. On each loop iteration, $sku changes; execute() sends its current value.
  4. get_result() returns a mysqli_result from which rows are fetched as arrays. fetch_assoc() returns null when there are no (more) rows.
  5. The statement is prepared once and executed three times.

Type Characters for bind_param()

CharacterType
iInteger
dDouble (float)
sString (also fine for dates and decimals)
bBlob, sent in packets with send_long_data()

 

The type string has one character per placeholder, in order: bind_param('sdi', $name, $price, $stock).


Shortcuts in Modern PHP

MethodPHPUsage
prepare() + bind_param() + execute()AllFull control; best when executing many times with explicit types
$stmt->execute([$a, $b])8.1+Pass values directly; all are sent as strings
$db->execute_query($sql, [$a, $b])8.2+Prepare, bind, and execute in one call; returns a mysqli_result for SELECT, true otherwise

 

<?php
require __DIR__ . '/src/db.php';

$db = db();

// One-off query: execute_query()
$customer = $db->execute_query('SELECT name, city FROM customers WHERE id = ?', [3])->fetch_assoc();
echo "{$customer['name']} lives in {$customer['city']}\n";

// Repeated execution: prepare once, execute with arrays
$stmt = $db->prepare('SELECT name FROM products WHERE id = ?');
foreach ([2, 5] as $id) {
    $stmt->execute([$id]);
    echo "Product $id: " . $stmt->get_result()->fetch_column() . "\n";
}

 

Output

Charu lives in Chennai
Product 2: Notebook A5
Product 5: Wireless Mouse

 

Sending values as strings works for almost all queries, because MySQL converts them to the column types. One notable exception is LIMIT, which needs a real integer; bind it with bind_param('i', ...). (fetch_column() returns the first column of the next row; it was added in PHP 8.1.)


Result Types With Prepared Statements

Prepared statements use MySQL's binary protocol, which returns integers and floats as native PHP types:

<?php
$row = db()->execute_query('SELECT id, stock, price FROM products WHERE sku = ?', ['PEN-01'])->fetch_assoc();

var_dump($row['id'], $row['stock'], $row['price']);

 

Output

int(1)
int(120)
string(5) "20.00"

 

DECIMAL values are always returned as strings, which preserves their exact value. Convert them deliberately, for example to integer paise for calculations, or format them directly for display.


Dynamic IN (...) Lists

A placeholder represents exactly one value. For a list, generate one placeholder per element:

<?php
$skus = ['PEN-01', 'MOUSE-01', 'NOPE-99'];

$placeholders = implode(', ', array_fill(0, count($skus), '?'));

$result = db()->execute_query(
    "SELECT name FROM products WHERE sku IN ($placeholders) ORDER BY id",
    $skus
);

echo implode(', ', array_column($result->fetch_all(MYSQLI_ASSOC), 'name')) . "\n";

 

Output

Gel Pen, Wireless Mouse

 

An empty list would produce invalid SQL (IN ()), so check for $skus === [] before querying.


What Cannot Be Bound: Identifiers

Placeholders work only for values. Table names, column names, sort directions, and SQL keywords cannot be parameters. When they depend on input (such as a "sort by" option), map the input to an allow-list:

<?php
$sortOptions = [
    'price_asc' => 'price ASC',
    'price_desc' => 'price DESC',
    'name' => 'name ASC',
];

$sort = $sortOptions[$_GET['sort'] ?? ''] ?? 'name ASC';

$stmt = db()->prepare("SELECT name, price FROM products ORDER BY $sort LIMIT ?");
$limit = 2;
$stmt->bind_param('i', $limit);
$stmt->execute();

foreach ($stmt->get_result() as $row) {
    echo "{$row['name']}: ₹{$row['price']}\n";
}

 

Output (for ?sort=price_desc)

Desk Lamp: ₹1299.00
Backpack: ₹899.00

 

Only SQL fragments written in your code can reach the query; the user merely chooses between them. LIMIT is bound as an integer with bind_param('i', ...). A mysqli_result can be iterated directly with foreach.


Older Style: bind_result()

Without get_result() (rare today; it requires the standard mysqlnd driver), results are bound to variables:

<?php
$stmt = db()->prepare('SELECT name, stock FROM products WHERE category = ? ORDER BY id');
$category = 'stationery';
$stmt->bind_param('s', $category);
$stmt->execute();
$stmt->bind_result($name, $stock);

while ($stmt->fetch()) {
    echo "$name ($stock)\n";
}

 

Output

Gel Pen (120)
Notebook A5 (45)

 

fetch() fills the bound variables with the next row and returns null when there are no more rows.


Common Mistakes

Concatenating Values Into SQL "Because It Is Internal"

Effect: Values from databases, files, or APIs can also contain quotes or malicious content.

Fix: Use placeholders for every value.

Quoting Placeholders

Effect: WHERE email = '?' searches for a literal question mark.

Fix: Write placeholders without quotes: WHERE email = ?.

Trying to Bind Identifiers

Effect: Syntax errors or literal strings instead of column names.

Fix: Use allow-lists for table names, columns, and sort directions.

Binding Values Instead of Variables With bind_param()

Effect: bind_param('s', 'PEN-01') fails, because parameters are bound by reference.

Fix: Bind variables, or pass values to execute([...]) / execute_query().

Mismatched Type String

Effect: An error is thrown when the number of type characters differs from the number of bound variables or placeholders.

Fix: Use exactly one type character per placeholder.


Best Practices

  • Use prepared statements for every query that contains values from outside the code.
  • Use execute_query() for one-off queries and prepare() for repeated execution.
  • Generate placeholder lists for IN (...); never interpolate the values.
  • Map dynamic identifiers (columns, sort orders) to allow-listed SQL fragments.
  • Treat DECIMAL results as strings and convert deliberately.

Official reference: https\://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery
Ask about this post
AI Ask about this post

Ask questions about MySQL Prepared and get answers drawn from it.

Signed-in readers only.