PHP Database Security
Database security is critical! Prepared statements protect against SQL injection - one of the most common and dangerous web vulnerabilities. Always use them!
Output
Click Run to execute your code
PDO Prepared Statements
<?php
// SECURE - Named parameters
$sql = "SELECT * FROM users WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(['email' => $_POST['email']]);
// SECURE - Positional parameters
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([1]);
?>
MySQLi Prepared Statements
<?php
$sql = "SELECT * FROM users WHERE email = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_POST['email']); // s = string
$stmt->execute();
$result = $stmt->get_result();
?>
โ ๏ธ NEVER Do This!
<?php
// VULNERABLE TO SQL INJECTION!
$sql = "SELECT * FROM users WHERE email = '{$_POST['email']}'";
$result = $pdo->query($sql); // DON'T DO THIS!
?>
Security Best Practices
- โ Always use prepared statements
- โ Never concatenate user input into SQL
- โ Validate and sanitize all input
- โ Use appropriate data types
- โ Limit database user permissions
- โ Use HTTPS for sensitive data
Summary
- Prepared statements: Prevent SQL injection
- PDO: Use named (:param) or positional (?) parameters
- MySQLi: Use bind_param()
- Never: Concatenate user input into SQL
What's Next?
Congratulations! You've completed Module 10 (Database). You now have complete PHP mastery from basics to databases!
Enjoying these tutorials?