Lesson 12 โข Expert
Database Integration (MySQL) ๐๏ธ
Connect PHP to MySQL with PDO โ perform CRUD operations, use prepared statements, transactions, and protect against SQL injection.
What You'll Learn in This Lesson
- โข Connecting to MySQL with PDO (recommended) and MySQLi
- โข CRUD: Create, Read, Update, Delete operations
- โข Prepared statements to prevent SQL injection
- โข Transactions for atomic multi-query operations
- โข Fetch modes and best practices for production
Try It: CRUD Operations
Insert, select, update, and delete data with PDO prepared statements
// PHP + MySQL CRUD Operations (simulated in JavaScript)
console.log("=== Connecting to MySQL ===");
console.log();
console.log("Two options: MySQLi or PDO");
console.log();
console.log("// PDO (recommended โ works with any database)");
console.log("$pdo = new PDO(");
console.log(" 'mysql:host=localhost;dbname=my_app;charset=utf8mb4',");
console.log(" 'username', 'password',");
console.log(" [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]");
console.log(");");
console.log();
// Simulate
...Try It: Security & Transactions
Prevent SQL injection, use named parameters, transactions, and compare PDO vs MySQLi
// Database Security & Best Practices
console.log("=== SQL Injection: The #1 Vulnerability ===");
console.log();
// BAD example
console.log("โ NEVER DO THIS:");
console.log(' $sql = "SELECT * FROM users WHERE name = \'$name\'";');
console.log();
console.log(" If $name = \' OR 1=1 --");
console.log(" Query becomes:");
console.log(" SELECT * FROM users WHERE name = '' OR 1=1 --'");
console.log(" โ Returns ALL users! ๐");
console.log();
// GOOD example
console.log("โ
ALWAYS USE PREPARED STA
...โ ๏ธ Common Mistakes
? or :name placeholders.ERRMODE_EXCEPTION, PDO silently fails. Always set it on connection.๐ Quick Reference โ PDO
| Method | Purpose |
|---|---|
| prepare() + execute() | Safe parameterized queries |
| fetch(FETCH_ASSOC) | Get one row as array |
| fetchAll(FETCH_ASSOC) | Get all rows as array |
| beginTransaction() | Start a transaction |
| commit() / rollBack() | Finish or undo transaction |
| lastInsertId() | Get ID of last inserted row |
๐ Lesson Complete!
You can now connect PHP to a database securely! Next, learn comprehensive security best practices to protect your web application.
Sign up for free to track which lessons you've completed and get learning reminders.