All posts
PHPNovember 15, 20268 min read

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.

F
Fepiq Team
Fepiq

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.

What is PDO in PHP?

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 PostgreSQL

What is SQL injection (and why you should care)?

SQL 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
<?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.

How a prepared statement works

A prepared statement has two steps. They happen in this order:

  1. Prepare: you send the SQL with placeholders (empty slots) to the database. The database reads and understands the query shape.
  2. Execute: you send the real values. The database puts them into the slots as plain data, never as SQL code.

Because the query shape is fixed before the values arrive, the values can never change what the query does. That is the whole trick.

Your first prepared statement with a ? placeholder

The simplest placeholder is a question mark. Each ? will be replaced by one value, in order.

php
<?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.

Named placeholders (easier to read)

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
<?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.

StyleLooks likeBest for
Question markWHERE id = ?Short queries with one or two values
NamedWHERE id = :idLonger queries, easier to read

INSERT, UPDATE and DELETE with prepared statements

The same pattern works for every kind of query. Here is how to add a new user from a form.

php
<?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
<?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.

Setting up PDO the safe way

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
<?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.

Common beginner mistakes

  • Putting variables inside the SQL string, like "WHERE id = $id". Always use a placeholder instead.
  • Wrapping a placeholder in quotes, like ':name' in quotes. PDO adds quotes for you, so write :name alone.
  • Using a placeholder for a table or column name. Placeholders only work for values. Choose table and column names from a fixed list in your own code.
  • Forgetting the WHERE part in UPDATE or DELETE.
  • Showing raw database errors to visitors. Log them instead.

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 guide

Frequently asked questions

What is a prepared statement in PHP?+

A 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.

Do prepared statements stop SQL injection?+

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.

Is PDO better than mysqli?+

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.

What is the difference between ? and :name placeholders?+

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.

Are prepared statements slower?+

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 us

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.