With a connection open (from the previous lesson), PDO can run any SQL you already know from the SQL DML lesson — SELECT, INSERT, UPDATE, DELETE — all work the same way from PHP.
<?php
$stmt = $pdo->query("SELECT name, course FROM students");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($students as $student) {
echo $student["name"] . " — " . $student["course"] . "\n";
}
?>fetchAll(PDO::FETCH_ASSOC) returns exactly the shape you met in the Associative Arrays lesson — an array of associative arrays, one per row, keyed by column name.
Never build a query by directly gluing a variable into the SQL string. A prepared statement sends the query and the data separately, so the database never confuses "data" with "SQL code" — this is the single most important security practice in this entire lesson.
<?php
// NEVER do this:
// $stmt = $pdo->query("SELECT * FROM students WHERE name = '$name'");
// Do this instead:
$stmt = $pdo->prepare("SELECT * FROM students WHERE name = ?");
$stmt->execute([$name]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>This is not optional
Gluing a variable directly into a SQL string opens the door to SQL injection — a visitor typing something like anything' OR '1'='1 into a form field could rewrite your query's logic entirely, potentially reading or deleting data they were never meant to touch. Prepared statements close this off completely, because the database engine itself is what keeps data and code separate — this is not something to memorize and skip "for simple cases."
<?php
// INSERT
$stmt = $pdo->prepare("INSERT INTO students (name, course) VALUES (?, ?)");
$stmt->execute(["Priya", "Web Development"]);
// UPDATE
$stmt = $pdo->prepare("UPDATE students SET course = ? WHERE name = ?");
$stmt->execute(["Graphic Design", "Priya"]);
// DELETE
$stmt = $pdo->prepare("DELETE FROM students WHERE name = ?");
$stmt->execute(["Priya"]);
?>The ? placeholders are filled in, in order, by the array passed to execute() — named placeholders (:name instead of ?) are also available, and read more clearly once a query has several parameters.
This lesson closes out the PHP section by connecting it back to everything else on this site: the HTML you already know renders the page, the PHP in this section decides what data goes into it, and the SQL section is the full reference for everything you can ask a database to do once PHP hands it a query. From here, the practical next step is a small real project — a guestbook, a simple to-do list stored in a database — that uses all of it together.