Skip to content
PHP Logo

What are the risks associated with SQL injection in PHP and how can they be mitigated?

SQL injection in PHP occurs when user input is not properly sanitized before being used in SQL queries, allowing malicious users to execute arbitrary SQL code. To mitigate this risk, developers should use prepared statements and parameterized queries to separate SQL logic from user input.

php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();