Why PDO?
PDO (PHP Data Objects) is a modern, safe way to talk to databases. It supports prepared statements, which protect you from SQL injection, one of the most common web attacks.
Create a table
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE,
marks INT NOT NULL
);Connect
<?php
$pdo = new PDO(
"mysql:host=localhost;dbname=school;charset=utf8mb4",
"db_user",
"db_password",
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);Keep credentials in a config file outside the public web folder.
Create
$stmt = $pdo->prepare("INSERT INTO students (name, email, marks) VALUES (:name, :email, :marks)");
$stmt->execute([":name" => "Asha", ":email" => "asha@example.com", ":marks" => 88]);
echo "New ID: " . $pdo->lastInsertId();Read
$stmt = $pdo->prepare("SELECT * FROM students WHERE marks >= :min ORDER BY marks DESC");
$stmt->execute([":min" => 60]);
foreach ($stmt->fetchAll() as $row) {
echo htmlspecialchars($row["name"]) . " - " . $row["marks"] . "<br>";
}Update and Delete
$pdo->prepare("UPDATE students SET marks = :m WHERE id = :id")
->execute([":m" => 91, ":id" => 1]);
$pdo->prepare("DELETE FROM students WHERE id = :id")
->execute([":id" => 1]);The rule that prevents SQL injection
Never put user input directly into a SQL string.
// DANGEROUS - never do this
$pdo->query("SELECT * FROM students WHERE id = " . $_GET["id"]);
// SAFE
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = :id");
$stmt->execute([":id" => $_GET["id"]]);Practice
Build a student management page with a form to add students, a table to list them with search, and edit and delete buttons. Use POST and CSRF tokens for changes.
Next steps
Learn the WordPress course to see how PHP powers the world's most popular CMS.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Connect to a database with PDO and list records.
- Insert, update and delete a record with prepared statements.
- Hash a password with password_hash and check it with password_verify.
Common mistakes
- Building SQL by joining user input into the string.
- Storing passwords in plain text.
Quick check
Why use prepared statements?
They separate SQL from data and prevent SQL injection.
What does CRUD stand for?
Create, read, update, delete.