SQL Injection in PHP: What It Is and How to Prevent It With Prepared Statements
Never put user input directly into SQL. Use prepared statements with PDO or mysqli.
Reference guide. This guide is written from established practice and the official documentation of the tools involved. We have not yet tested every step on a live demo site. Back up your site before you change anything.
SQL injection happens when user input becomes part of the SQL command, letting attackers read or change your database.
Unsafe
$q = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";
Safe with PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
$rows = $stmt->fetchAll();
Rules
- Always use prepared statements with placeholders, for every value from users, cookies or URLs.
- Give the database user only the permissions it needs.
- Do not show database errors to visitors. See our PHP errors guide.
- Escape output with
htmlspecialchars()to prevent cross-site scripting. - Keep libraries and the PHP version updated. See our PHP version guide.
Connection problems
Related guides
- WordPress Login Page Keeps Reloading or Redirecting (Can't Log In)
- WordPress User Roles Explained: Administrator, Editor, Author, Contributor, Subscriber
- Unknown Administrator Users Appeared in WordPress: What to Do
- Lost Your Phone or Two-Factor Code for WordPress: How to Get Back In
Did this solve it? If not, email hello@sitefixlab.org with the exact error text and we will look into it. Try the problem finder.