0
0
PHPprogramming~5 mins

How SQL injection exploits unsafe queries in PHP

Choose your learning style9 modes available
Introduction

SQL injection happens when bad users put harmful commands into places where your program expects normal data. This can let them see or change your database without permission.

When you accept user input to search or filter data in a database.
When you build SQL queries by adding user input directly into the query string.
When you want to understand why your website or app might be unsafe.
When you want to learn how to protect your database from attackers.
Syntax
PHP
<?php
// Unsafe SQL query example
$user_input = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '$user_input'";
$result = mysqli_query($conn, $query);
?>

This example shows how user input is directly added to the SQL query.

This is unsafe because a user can add extra commands to the input.

Examples
User input is added directly to the query string, which is unsafe.
PHP
<?php
// Unsafe example
$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '$id'";
mysqli_query($conn, $query);
This uses a prepared statement to safely insert user input.
PHP
<?php
// Safe example using prepared statements
$id = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
Sample Program

This program shows how a user input like "1 OR 1=1" can make the query return all rows, not just one.

PHP
<?php
// Example showing SQL injection vulnerability
$conn = new mysqli('localhost', 'user', 'pass', 'testdb');

// Simulate user input that tries SQL injection
$user_input = "1 OR 1=1";

// Unsafe query
$query = "SELECT * FROM users WHERE id = '$user_input'";

// Run query
$result = $conn->query($query);

// Print number of rows returned
if ($result) {
    echo "Number of rows: " . $result->num_rows . "\n";
} else {
    echo "Query error";
}
?>
OutputSuccess
Important Notes

Never put user input directly into SQL queries.

Use prepared statements or parameterized queries to keep your database safe.

SQL injection can let attackers see or change data they should not access.

Summary

SQL injection happens when unsafe queries let users add harmful commands.

Always use safe methods like prepared statements to handle user input.

Protecting your database keeps your app and users safe.