Introduction to PHP + MySQL
Now let's connect SQL to a real web application. PHP is the server-side language behind WordPress, Wikipedia, and millions of other sites. Combined with MySQL, it powers dynamic web apps where data is stored, retrieved, and displayed on every page load.
Key Concepts
PDO — PHP Data Objects
PDO is PHP's modern database library. It supports MySQL, PostgreSQL, SQLite, and more. Use $pdo = new PDO('mysql:host=localhost;dbname=school', $user, $pass) to connect. Always use PDO — never concatenate user input directly into SQL strings.
Prepared Statements
A prepared statement separates SQL from data. $stmt = $pdo->prepare('SELECT * FROM students WHERE grade = ?'); $stmt->execute([$grade]); This prevents SQL injection — the most common web vulnerability. The database treats ? as data, not as SQL code.
Fetching Results
$stmt->fetch(PDO::FETCH_ASSOC) returns one row as an array. $stmt->fetchAll(PDO::FETCH_ASSOC) returns all rows. Loop through results with foreach($rows as $row){ echo $row['name']; } to build dynamic HTML from database data.
🆕 PHP + MySQL Code Walkthrough
Study a complete, secure PHP script that reads from a database and outputs HTML.
$pdo = new PDO('mysql:host=localhost;dbname=school', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 2. Safe user input (never put $_GET directly in SQL!)
$grade = (int) $_GET['grade'] ?? 10;
// 3. Prepared statement prevents SQL injection
$stmt = $pdo->prepare('SELECT name, gpa FROM students WHERE grade = ? ORDER BY gpa DESC');
$stmt->execute([$grade]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 4. Output HTML from results
foreach ($students as $row) {
echo '<li>' . htmlspecialchars($row['name']) . ' — GPA: ' . $row['gpa'] . '</li>';
}
1 OR 1=1; DROP TABLE students in a form field and destroy your database. Prepared statements make that impossible.<script>steal()</script> could inject JavaScript into your page. htmlspecialchars converts < to < — the XSS defense.✅ Check Your Understanding
1. What does a prepared statement prevent?
2. What does htmlspecialchars() do in PHP?
3. What does PDO::FETCH_ASSOC return?