PDO and SQL
Connect with PDO, use prepared statements and fetch typed rows.
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.
<?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
MediumFetch one lesson
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.