Introduction to PHP + MySQL
Connect a server-side language to a database. Learn how PHP talks to MySQL using PDO with prepared statements — the industry-standard pattern for web backends.
PHP + MySQL Code Viewer
Click each pattern to see how PHP interacts with MySQL — from connecting to safe parameterized queries.
The PHP + MySQL Web Stack
PHP is a server-side scripting language that runs on your web server. When a user submits a form or requests a page, PHP executes, queries the MySQL database, and sends HTML back to the browser. The database never communicates with the browser directly — PHP is the intermediary.
The classic LAMP stack: Linux OS, Apache web server, MySQL database, PHP language. Still powers roughly 80% of web servers including WordPress.
Connecting with PDO
A PDO connection requires a DSN (Data Source Name), username, and password. Always set the error mode to ERRMODE_EXCEPTION so PHP throws exceptions instead of silently failing. Store credentials in environment variables or a config file outside the web root — never hard-code passwords in source code.
Prepared Statements
Prepared statements are the single most important PHP + MySQL security practice. Instead of embedding user input directly into a SQL string, you use ? or :named placeholders. The database driver separates SQL code from data, making SQL injection structurally impossible.
Workflow: $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"), then $stmt->execute([$email]). The driver handles escaping internally.
"SELECT * FROM users WHERE name = '" . $_GET['name'] . "'"), an attacker can inject ' OR '1'='1 and dump your entire database. Prepared statements completely prevent this attack.
Fetching Results
After executing a SELECT, use fetch methods to retrieve rows:
$stmt->fetch(PDO::FETCH_ASSOC)— one row as associative array$stmt->fetchAll(PDO::FETCH_ASSOC)— all rows as array of arrays$stmt->fetchObject()— row as anonymous object$stmt->rowCount()— number of affected rows (INSERT/UPDATE/DELETE)
INSERT and lastInsertId
After an INSERT, retrieve the auto-generated primary key with $pdo->lastInsertId(). This is useful when you need to immediately create related rows in another table (e.g., create a user row then create their profile row using the new user_id).
Transactions in PHP
PDO exposes the same transaction control commands through PHP methods: $pdo->beginTransaction(), $pdo->commit(), and $pdo->rollback(). Wrap them in a try-catch so exceptions automatically trigger rollback.
Check Your Understanding
1. Why are prepared statements preferred over concatenating user input into SQL strings?
2. Which PDO method retrieves ALL rows from a SELECT query as an array of associative arrays?
3. After INSERT INTO users ..., how do you retrieve the auto-generated primary key in PDO?
4. In a PHP try-catch block wrapping a transaction, what should the catch block do?