Web Analytics

PHP Database Security

Intermediate~30 min read

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!