Skip to content
PHP Logo

What are the best practices for handling user input and database queries in PHP to prevent SQL injection attacks?

SQL injection attacks occur when malicious users input SQL commands into forms or URLs, which can then be executed by the database. To prevent this, use prepared statements with parameterized queries when interacting with databases in PHP. This ensures that user input is treated as data rather than executable code.

php
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

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

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

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