PHP PDO Prepared Statements for Beginners (Simple Guide)
Learn PHP PDO prepared statements step by step. Understand SQL injection in plain English and write safe database queries with copy-paste examples.
Learn PHP PDO prepared statements step by step. Understand SQL injection in plain English and write safe database queries with copy-paste examples.
If you searched for "PHP PDO prepared statements for beginners", here is the short answer. A prepared statement is a way to send an SQL query to the database with empty slots, and then fill those slots with values separately. Because the values never get mixed into the query text, a hacker cannot sneak in harmful SQL. This is the safe way to talk to a database from PHP.
In this guide, you will learn what PDO is, what SQL injection is, and how to write safe queries for SELECT, INSERT, UPDATE and DELETE. No experience is needed. Every term is explained the first time we use it.
PDO stands for PHP Data Objects. It is a tool built into PHP that lets your code talk to a database. A database is a place where an app stores its data, such as users, products or posts. PDO works with many databases, including PostgreSQL and MySQL, using almost the same code.
If you have not connected PHP to a database yet, read our guide first and then come back here.
New to PDO? Learn how to make the connection first.
Connect PHP to PostgreSQLSQL is the language we use to ask a database for data. SQL injection is an attack where a user types SQL code into a form field, and your app runs it by mistake. It happens when you build a query by gluing user input into a string.
Look at this unsafe example. Never write code like this.
<?php
$email = $_POST['email'];
// UNSAFE: user input is pasted into the query
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = $pdo->query($sql);Line 2 reads what the user typed in a form. Line 5 pastes it directly inside the SQL text. If a user types ' OR '1'='1 as their email, the query becomes true for every row, and the attacker can see all your users. Worse input could delete data. Prepared statements stop this problem.
A prepared statement has two steps. They happen in this order:
Because the query shape is fixed before the values arrive, the values can never change what the query does. That is the whole trick.
The simplest placeholder is a question mark. Each ? will be replaced by one value, in order.
<?php
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
$user = $stmt->fetch();
if ($user) {
echo 'Welcome, ' . htmlspecialchars($user['name']);
} else {
echo 'No user found.';
}Line 2 prepares the query. The ? is the empty slot. Line 3 runs it and gives the email inside a list (an array). Line 4 fetches one row as an array, or false if nothing matched. Lines 6 to 10 check the result. The function htmlspecialchars makes the text safe to show on a web page.
When a query has many values, question marks get confusing. Named placeholders start with a colon, like :email. You give each value a name.
<?php
$sql = 'SELECT * FROM users WHERE email = :email AND active = :active';
$stmt = $pdo->prepare($sql);
$stmt->execute([
'email' => $_POST['email'],
'active' => true,
]);
$users = $stmt->fetchAll();Line 2 has two named slots: :email and :active. Lines 4 to 7 pass an array where each key matches a slot name. Line 8 uses fetchAll to get every matching row as a list of arrays. Named placeholders let you write the values in any order.
| Style | Looks like | Best for |
|---|---|---|
| Question mark | WHERE id = ? | Short queries with one or two values |
| Named | WHERE id = :id | Longer queries, easier to read |
The same pattern works for every kind of query. Here is how to add a new user from a form.
<?php
$sql = 'INSERT INTO users (name, email) VALUES (:name, :email)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
'name' => $_POST['name'],
'email' => $_POST['email'],
]);
echo 'Rows added: ' . $stmt->rowCount();Line 2 writes an INSERT query with two slots. Lines 4 to 7 fill them with form data. Line 9 uses rowCount to show how many rows were changed. Here it should print 1.
Updating and deleting look almost the same. Always include a WHERE part, or you will change every row.
<?php
// UPDATE
$stmt = $pdo->prepare('UPDATE users SET name = :name WHERE id = :id');
$stmt->execute(['name' => 'Sam', 'id' => 5]);
// DELETE
$stmt = $pdo->prepare('DELETE FROM users WHERE id = :id');
$stmt->execute(['id' => 5]);The UPDATE changes the name of the user whose id is 5. The DELETE removes that same user. In both cases the id and name travel as separate values, so they stay safe.
When you create your PDO connection, turn on exceptions. An exception is PHP's way of stopping and telling you when something goes wrong, instead of failing quietly.
<?php
$pdo = new PDO(
'pgsql:host=localhost;dbname=myapp',
'myuser',
'mypassword',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);Lines 3 to 5 give the database address, username and password. Line 7 makes PDO throw an error you can see if a query fails. Line 8 makes every fetched row an easy array with column names as keys. Use mysql: instead of pgsql: if you use MySQL.
Prepared statements protect your queries, but you should still check user input. Our form validation guide shows how.
Next step: make sure the data is valid before it reaches your database.
Read the PHP form validation guideA prepared statement is an SQL query with placeholders that is sent to the database first. The real values are sent afterward as plain data. This keeps user input separate from the SQL code.
Yes, for the values you pass in, they stop SQL injection very well. The database treats those values only as data, never as commands. You must still avoid building table or column names from user input.
Both support prepared statements. PDO works with many databases such as PostgreSQL, MySQL and SQLite, while mysqli only works with MySQL. Beginners often prefer PDO because one skill works everywhere.
A question mark is filled by position, in order. A named placeholder like :email is filled by its name. Named ones are easier to read in longer queries.
For normal beginner apps, you will not notice any difference. Safety is far more important. Prepared statements can even be faster when you run the same query many times.
Want help building a safe, fast PHP application? Talk to the Fepiq team.
Contact usOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL AND, OR and NOT operators with simple examples. See how to combine conditions in WHERE and avoid the common mistakes beginners make.
Learn JavaScript template literals with simple examples: backticks, ${} variables, and multi-line strings. A beginner-friendly guide you can copy and run.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.