PHP for the Web·PHP from first script to a working app

PDO and SQL

Connect with PDO, use prepared statements and fetch typed rows.

Beginner 16 min read Lesson 8 of 300 Challenge included
What you will be able to do
  • Create PDO once and reuse it.
  • Use named or positional placeholders, never string concatenation.
  • Set ERRMODE_EXCEPTION.
  • Fetch with FETCH_ASSOC in application code.

In plain English

PDO gives one API for several databases. Prepared statements send SQL and data separately, which prevents SQL injection and lets the database reuse a plan. Set exceptions on so failures are impossible to ignore.

db.phpPHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=edubyte;charset=utf8mb4', 'app', 'secret', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$stmt = $pdo->prepare('SELECT title FROM lessons WHERE course_slug = :course ORDER BY title');
$stmt->execute(['course' => 'css']);
$titles = $stmt->fetchAll();

print_r($titles);
Your turn

Fetch one lesson

Medium

Write a prepared statement that selects the title of the lesson with id 7.

PHP · starter
$stmt = $pdo->prepare(...);
Check your understanding before moving on.
Knowledge checkQuestion 1

What is the main security benefit of a prepared statement?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Classes and namespaces
Lesson 8 of 300 · 0% of course