Prevent SQL Injection with PDO and Prepared Statements

Learn how to secure your database queries with prepared statements and PDO in PHP.

2 min read โ€ข
170 1 0

Learn how to write secure PHP code that protects your database from SQL injection attacks using PDO and prepared statements.

๐Ÿ›ก๏ธ What is SQL Injection?

SQL injection is a common attack where malicious users insert SQL code into your application's input fields to access, manipulate, or delete database information. It can lead to severe data breaches and is one of the most dangerous web security risks.

โŒ Insecure Query Example

This code is vulnerable to SQL injection:

<?php $username = $_GET['username']; $query = "SELECT * FROM users WHERE username = '$username'"; $result = mysqli_query($conn, $query); ?>

If a user inputs admin' OR '1'='1, it can return all users in the table!

โœ… Using PDO with Prepared Statements

Prepared statements separate the SQL logic from user input, making injections nearly impossible.

๐Ÿ“Œ Step-by-step:

<?php $pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username = $_GET['username']; $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username"); $stmt->execute(['username' => $username]); $user = $stmt->fetch(); ?>

The :username placeholder is replaced securely by PDO with the actual value.

๐Ÿ“ Insert with Prepared Statement

<?php $stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)"); $stmt->execute([ 'username' => 'newuser', 'email' => '[email protected]' ]); ?>

This ensures all data is escaped and safe before hitting the database.

๐Ÿ”’ Best Practices

  • Always use prepared statements , never insert raw user input directly into SQL queries
  • Validate and sanitize input even when using PDO
  • Use named parameters (:param) for clarity and flexibility
  • Never use dynamic SQL unless absolutely necessary , and even then, parameterize it

๐Ÿงพ Summary

Preventing SQL injection is essential for secure PHP applications. By using PDO and prepared statements, you ensure that user data is safely separated from SQL logic. Combined with proper input validation, your app will be well-protected against one of the webโ€™s most dangerous vulnerabilities.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel