SQL Injection in PHP

What is SQL Injection? 

SQL Injection happens when an attacker sneaks harmful SQL code into your database queries. If your PHP app isn't secure:

  • Steal sensitive user data (passwords, emails, credit cards)
  • Modify or delete your entire database 
  • Take full control of your application 

Example of a Vulnerable PHP Code (Bad Code!)

// Danger! This code is vulnerable to SQL Injection!
$username = $_GET['username'];
$password = $_GET['password'];

$conn = new mysqli("localhost", "root", "", "mydatabase");
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $conn->query($query);

What Can a Hacker Do?

If an attacker enters this as the username:

admin' --

The final SQL query becomes:

SELECT * FROM users WHERE username = 'admin' --' AND password = ''

That -- turns the rest of the query into a comment, making it always return admin’s account

How to Prevent SQL Injection?

The solution is simple: Always use prepared statements and parameterized queries!

Secure Code Using MySQLi (Prepared Statements)

$conn = new mysqli("localhost", "root", "", "mydatabase");
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

Secure Code Using PDO (Recommended!)

$conn = new PDO("mysql:host=localhost;dbname=mydatabase", "root", "");
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $password);
$stmt->execute();
$result = $stmt->fetchAll();

Using PDO is even better because it supports multiple database types and better error handling. 

Bonus: Extra Security Tips 

 Always validate user input – Use regex or built-in PHP functions like filter_var()Use least privilege principle – Don’t give database users full control.  Escape output, not input – Prevent XSS by using htmlspecialchars() when displaying user data.  Enable Web Application Firewall (WAF) – Extra protection never hurts!

Post a Comment

0 Comments